각 컴포넌트는 하위 컴포넌트에게 prop을 통해 특정 데이터 전달을 수행한다.
prop은 목적지 컴포넌트로 가는 모든 컴포넌트를 거치기 때문에, 이런 컴포넌트의 깊이가 너무 깊어지면 코드가 굉장히 복잡해질 수 있다. 이것을 props drilling이라 하며, props drilling을 피하기 위해 useContext 와 Context API를 사용한다.
간단하고 이해하기 쉽게만 설명한다면 아래와 같이 설명할 수 있다.
1. 상위 컴포넌트에서 어떤 데이터가 필요한 곳이 있는지 broadcast를 한다.
2. 하위 컴포넌트 중에서 해당 데이터가 필요한 곳에서는 이를 불러 쓴다.
코드로는 아래와 같이 사용할 수 있다.
app.js
<!-- app.js-->
import { ThemeContext } from './context/ThemeContext';
function App() {
const [isDark,setIsDark] = useState(false);
return (
<ThemeContext.Provider value ={{isDark,setIsDark}}>
<Page/>
</ThemeContext.Provider>
)
}
context이름.Provider 를 통해 태그 안에 위치한 컴포넌트들에게 특정 값을 방송할 수 있다. 이 때, value={} 를 통해서 값을 지정한다.
Theme.Context.js
<!--'./context/ThemeContext.js'-->
import {createContext} from 'react';
export const ThemeContext = createContext("hello");
Context를 만들 때에는 createContext(초기화값) 을 통해 생성해준다.
Header.js
<!-- './components/Header.js'-->
import React, { useContext } from 'react';
import { ThemeContext } from '../context/ThemeContext';
const Header =()=>{
const {isDark} = useContext(ThemeContext);
return (
<header
className='header'
style={{
backgroundColor:isDark ? 'black':'lightgray',
color:isDark? 'white':'black',
}}>
<h1>Welcome!</h1>
</header>
);
};
export default Header;
Header 컴포넌트는 Page컴포넌트의 자식 컴포넌트이다. ThemeContext의 isDark값이 필요하여 useContext를 통해 값을 가져온것을 확인할 수 있다.