[요약] 슬기로운 useContext 사용법

DL·2022년 9월 5일
0

요약

1. 전역적 상태관리를 하기 위한 훅, useContext 라는 것이 있다.

2. 주요한 예약어로는 createContext, Context.Provider, useContext 등이 있다.

3. 사용법은 아래 코드와 같다.

/* DarkModeContext.js */
export const DarkModeContext = createContext();

export const DarkModeProvider = ({ children }) => {
	const [ isDark, setIsDark ] = useState(false);
  
	return (
    	<DarkModeContext.Provider value={{isDark, setIsDark}}>
      		{children}
      	</DarkModeContext.Provider>
    );
}

/* App.js */
function App = () => {
	return (
    	<DarkModeProvider>
      		<ModeButton />
      	</DarkModeProvider>
    );
}

/* ModeButton */
const ModeButton = () => {
  	const { isDark, setIsDark } = useContext(DarkModeContext);
	return (
    	<button onClick={() => setIsDark((prev) => !prev)}>dark mode</button>
    );
}

참고

리액트 공식문서

profile
어제보다 오늘, 오늘보다 내일 더 성장하는 프론트엔드 개발자

0개의 댓글