createContext
: context 생성useContext
: context를 구독하고 해당 context의 현재값을 읽는다Provider
: context를 하위 컴포넌트에게 전달context로 관리 시, context파일을 생성하여 하위 파일을 생성 후 관리하면 된다.
// React와 필요한 훅들을 불러온다
import React, { createContext, useContext, useState } from 'react';
// 컨텍스트 생성: 테마 관련 정보를 전역적으로 관리하기 위한 컨텍스트를 생성
const ThemeContext = createContext();
// ThemeProvider 컴포넌트: 테마 관련 상태와 함수를 제공하는 컴포넌트
const ThemeProvider = ({ children }) => {
// 테마 상태를 'light'로 초기화
const [theme, setTheme] = useState('light');
// 테마를 전환하는 함수 현재 테마가 'light'이면 'dark'로, 'dark'이면 'light'로 전환
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
// ThemeContext.Provider를 사용하여 테마 상태와 토글 함수를 자식 컴포넌트에게 전달
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
// ThemedComponent 컴포넌트: 실제로 테마를 사용하는 컴포넌트
const ThemedComponent = () => {
// useContext 훅을 사용해 ThemeContext에서 테마 관련 정보를 가져온다
const { theme, toggleTheme } = useContext(ThemeContext);
// 현재 테마에 따라 스타일을 조정하여 렌더링
//테마 전환 버튼을 포함
return (
<div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
<p>현재 테마: {theme}</p>
<button onClick={toggleTheme}>테마 변경</button>
</div>
);
};
// App 컴포넌트: 애플리케이션의 루트 컴포넌트 ThemeProvider로 ThemedComponent를 감싸 테마 기능을 제공
const App = () => {
return (
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
};
export default App;
이 부분을 이해를 못해서 정말 많이 헤메고 고민도 많이 했던 훅이였다.. 지금도 100프로의 이해는 없고 5-60프로 정도 이해하지 않았나 싶다..
단순히 개념을 보는 것 보다 코드 연습을 통해서 익숙해지는 게 좋은 방법이 아닐까 싶다.