본문 바로가기
Programming

React Context API

by 나무수피아는 지식의 가지를 뻗어가는 공간입니다. 2025. 10. 29.
반응형

Context API 사용법

Context API는 React 애플리케이션에서 컴포넌트 간에 전역 상태를 공유할 수 있는 방법입니다. props를 일일이 전달하지 않고도 데이터를 공유할 수 있어 매우 유용합니다.

1. Context API란?

React의 Context는 전역적인 데이터 저장소입니다. 예를 들어 로그인 정보, 테마 설정, 언어 설정 등과 같이 여러 컴포넌트에서 접근해야 하는 데이터를 효율적으로 관리할 수 있습니다.

2. 기본 구조

  1. Context 생성
  2. Provider로 감싸기
  3. useContext로 소비
// ThemeContext.js import { createContext } from 'react'; const ThemeContext = createContext(); export default ThemeContext;
// App.jsx import React, { useState } from 'react'; import ThemeContext from './ThemeContext'; import Page from './Page'; function App() { const [theme, setTheme] = useState('light'); return ( <ThemeContext.Provider value={{ theme, setTheme }}> <Page /> </ThemeContext.Provider> ); } export default App;
// Page.jsx import React, { useContext } from 'react'; import ThemeContext from './ThemeContext'; function Page() { const { theme, setTheme } = useContext(ThemeContext); return ( <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}> <h2>현재 테마: {theme}</h2> <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}> 테마 전환 </button> </div> ); } export default Page;

3. 정리

  • props drilling 없이 상태 공유 가능
  • 컴포넌트 구조가 복잡해질수록 유용
  • Provider는 반드시 상위에 존재해야 함
💡 팁: 여러 Context를 사용할 때는 각각의 Provider를 중첩해서 사용하거나, 커스텀 Provider로 추상화할 수 있습니다.

4. 다음 강의 예고

다음 시간에는 useReducer + Context API 조합으로 더 강력한 전역 상태 관리 방법을 알아봅니다!

반응형

'Programming' 카테고리의 다른 글

React 상태관리 도구 비교 (Context vs Redux)  (75) 2025.10.31
React Router  (73) 2025.10.30
React 커스텀 Hook 만들기  (68) 2025.10.28
React 컴포넌트 분리 및 재사용  (65) 2025.10.27
React useEffect  (41) 2025.10.26