[소플의 처음 만난 리액트] 14장 실습문제

이 포스트에서는 리액트 컴포넌트 트리 내에서 데이터를 공유하기 위해 컨텍스트를 활용하는 방법을 학습했습니다. 컨텍스트를 이용하면 중간에 있는 엘리먼트들에게 props를 넘겨주지 않고도 데이터를 제공할 수 있어 코드 최적화에 도움이 됩니다.
Jan 02, 2024
[소플의 처음 만난 리액트] 14장 실습문제

ThemeContext .jsx

import React from "react"; const ThemeContext = React.createContext(); ThemeContext.displayName = "ThemeContext"; export default ThemeContext;

MainContent.jsx

import React, { useContext } from "react"; import ThemeContext from "./ThemeContext"; function MainContent(props) { const { theme, toggleTheme } = useContext(ThemeContext); return ( <div style={{ width: "100vw", height: "100vh", padding: "1.5rem", backgroundColor: theme == "light" ? "white" : "black", color: theme == "light" ? "black" : "white", }} > <p>안녕하세요, 테마 변경이 가능한 웹사이트 입니다.</p> <button onClick={toggleTheme}>테마 변경</button> </div> ); } export default MainContent;

DarkOrLight.jsx

import React, { useState, useCallback } from "react"; import ThemeContext from "./ThemeContext"; import MainContent from "./MainContent"; // 컨텍스트를 사용하여 테마 변경 기능 만들기 function DarkOrLight(props){ const [theme, setTheme] = useState("light") // 의존성 배열에 있는 값이 변경될 경우에만 재렌더링 const toggleTheme = useCallback(()=>{ if(theme == "light"){ setTheme("dark"); }else if(theme == "dark"){ setTheme("light"); } },[theme]); return ( <ThemeContext.Provider value={{theme, toggleTheme}}> <MainContent /> </ThemeContext.Provider> ); } export default DarkOrLight;
 

핵심 키워드

  • 컨텍스트란 리액트 컴포넌트 트리 내에서 글로벌하게 참조할 수 있는 데이터를 공유할 수 있는 방법이다. 컨텍스트를 이용하면 단계마다 일일이 props를 넘겨주지 않고도 컴포넌트 트리 전체에 데이터를 제공할 수 있다.
  • 불필요한 컴포넌트에게 일일이 props로 데이터를 받아서 넘기는 과정은 비생산적이다. 이럴 경우 컨텍스트를 이용하면 중간에 있는 엘리먼트들에게 props를 넘겨주지 않을 수 있다.
 

결론!

해당 문제를 풀면서 컨텍스트를 이용한 코드 최적화에 대해 이해할 수 있었다.
Share article
RSSPowered by inblog