props 대신 컴포넌트에 데이터를 넘겨주는 방식
왜 props를 대체하는가?
- 컴포넌트 간 관계가 깊어지면 깊어질수록 복잡해진다.
- 반복적인 코드의 계속된 작성은 비효율적
- 따라서 컨텍스트를 통해 한번에 데이터를 전달한다.
컨텍스트의 예시
1. ThemeContext.jsx
javascript
import React from "react";
const ThemeContext = React.createContext();
ThemeContext.displayName = "ThemeContext";
export default ThemeContext;
- ThemeContext는
React.createContext()를 사용하여 생성되었습니다. - 이 컨텍스트는 ThemeContext 객체를 만들어 내보내며, 이를 통해 트리 구조의 하위 컴포넌트에서 테마 데이터를 접근할 수 있게 한다.
2. DarkOrLight.jsx
javascript
import { useState, useCallback } from "react";
import ThemeContext from "./ThemeContext";
import MainContent from "./MainContext";
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;
- DarkOrLight 컴포넌트는 ThemeContext.Provider를 사용하여 컨텍스트 값을 하위 컴포넌트에 제공하고 있습니다.
- theme와 toggleTheme 함수는 이 컴포넌트에서 관리되며, ThemeContext.Provider의 value prop으로 전달됩니다.
- ThemeContext.Provider로 래핑된 MainContent 컴포넌트는 이제 ThemeContext에 접근할 수 있습니다.
3. MainContext.jsx
javascript
import { 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;
- MainContent 컴포넌트는 useContext 훅을 사용하여 ThemeContext에 접근한다.
- useContext(ThemeContext)를 호출하면 ThemeContext.Provider에서 제공하는 현재의 theme와 toggleTheme 함수를 받을 수 있.
- 이 컴포넌트는 받은 theme에 따라 배경색과 글자색을 변경하고, toggleTheme 함수를 사용하여 테마를 변경할 수 있는 버튼을 렌더링한다.