컴포넌트에서 Context
를 읽고 subscribe할 수 있는 hook
const value = useContext(SomeContext)
Context 리액트 컴포넌트에서 Props가 아닌 또 다른 방식으로 컴포넌트간에 값을 전달하는 방법
props drilling의 대안임
createContext
로 Context 객체 생성
const SomeContext = createContext(defaultValue)
Context 객체 안에는 Provider와 Consumer라는 컴포넌트가 들어있다.
value
라는 props 안에 공유할 값을 추가하면 자식 컴포넌트에서 접근할 수 있다.
import { createContext, useContext } from 'react';
const ThemeContext = createContext(null);
export default function MyApp() {
return (
<ThemeContext.Provider value="dark">
<Form />
</ThemeContext.Provider>
)
}
이 방법은 추천하진 않지만 Context를 읽을 수 있는 방법 중 하나이다.
function Button() {
// 🟡 Legacy way (not recommended)
return (
<ThemeContext.Consumer>
{theme => (
<button className={theme} />
)}
</ThemeContext.Consumer>
);
}
useContext
hook은 context에 있는 value를 불러오는 역할이다.