보통 state의 이동은 한 단계씩 전달된다. state가 거쳐 가는 component가 많을수록 코드와 머릿속이 동시에 복잡해진다...
Context API는 global 하게state 값을을 관리해준다.원하는 곳에한 번에 값을 전해줄 수 있다.
const value = useContext(MyContext);
const themes = {
light: {
foreground: "#000000",
background: "#eeeeee"
},
dark: {
foreground: "#ffffff",
background: "#222222"
}
};
const ThemeContext = React.createContext(themes.light);
function App() {
return (
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}
<context객체명.Provider value={값}></ context객체명.Provider>
로 감싼다.useContext(context객체명)
를 변수에 담고, 사용하기 원하는 태그에서 value를 사용한다.