Ch.22 React 심화 — 상태 관리 패턴
useContext — React의 전역 상태
createContext와 Provider 패턴을 이해한다useContext 훅으로 값을 읽을 수 있다테마 전환 기능을 Context로 구현할 수 있다
모든 컴포넌트가 공유하는 저장소
로그인 유저 정보, 테마 설정 같은 데이터를 모든 컴포넌트에서 사용해야 하지만 Props Drilling은 싫습니다.
어디서든 바로 접근할 수 있는 공유 데이터를 만드는 방법은?
Context API — React 내장 기능으로, Provider로 감싼 모든 자식 컴포넌트가 데이터를 공유합니다.
article
핵심 내용
3단계로 Context를 만듭니다 생성 → 제공 → 사용
createContext: Context 객체 생성 (초기값 설정)
Provider: 공유할 데이터를 value로 전달
useContext: 자식 컴포넌트에서 값 사용
import { createContext, useContext, useState } from "react";
// 1. Context 생성
const UserContext = createContext<{ name: string } | null>(null);
// 2. Provider로 감싸기 (보통 App 또는 Layout에서)
function App() {
const [user] = useState({ name: "Kim" });
return (
<UserContext.Provider value={user}>
<Layout />
<Sidebar />
<Footer />
</UserContext.Provider>
);
}Provider의 역할 Provider로 감싼 모든 자식 컴포넌트는 중간 단계 없이 직접 데이터에 접근할 수 있습니다. Props Drilling 완전 해소!
어떤 깊이에서든 useContext 한 줄이면 됩니다
// 커스텀 훅으로 깔끔하게 만들기
function useUser() {
const context = useContext(UserContext);
if (!context) {
throw new Error("useUser는 UserProvider 안에서 사용하세요");
}
return context;
}
// 사용
function Header() {
const user = useUser(); // 깔끔!
return <h1>{user.name}님 환영합니다</h1>;
}바이브 코더 팁 useContext를 직접 쓰지 말고, 커스텀 훅(useUser)으로 감싸세요. 에러 처리가 한 곳에 모이고, 사용하는 곳이 깔끔해집니다.
라이트/다크 모드 전환 Context의 대표적 사용 사례입니다
// theme-context.tsx
import { createContext, useContext, useState } from "react";
type Theme = "light" | "dark";
const ThemeContext = createContext<{
theme: Theme;
toggle: () => void;
} | null>(null);
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
const toggle = () => setTheme(t => t === "light" ? "dark" : "light");
return (
<ThemeContext.Provider value={{ theme, toggle }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("ThemeProvider 필요");
return ctx;
}// 사용하는 곳 — 어디서든!
function ThemeToggle() {
const { theme, toggle } = useTheme();
return (
<button onClick={toggle}>
{theme === "light" ? "🌙 다크 모드" : "☀️ 라이트 모드"}
</button>
);
}
function Page() {
const { theme } = useTheme();
return (
<div className={theme === "dark" ? "bg-gray-900" : "bg-white"}>
<ThemeToggle />
<h1>콘텐츠</h1>
</div>
);
}Context를 사용하기 위한 3단계 순서는?
Provider 바깥에 있는 컴포넌트도 useContext로 값을 읽을 수 있다
Context가 가장 적합한 사용 사례는?
edit_note
정리 노트
useContext 핵심 정리
Context API 구성
- createContext
- Context 객체를 생성하고 기본값을 설정
- Provider
- 하위 컴포넌트에 데이터를 공급하는 래퍼 컴포넌트
- useContext
- 하위 컴포넌트에서 Provider의 값에 직접 접근하는 훅
최적 사용처
- 테마
- 다크/라이트 모드 등 앱 전체 테마 관리
- 유저 정보
- 로그인 상태, 유저 프로필 등 전역 인증 정보
★
Context는 자주 변경되는 데이터보다 테마/언어처럼 변경 빈도가 낮은 전역 데이터에 적합합니다.
퀴즈와 인터랙션으로 더 깊이 학습하세요
play_circle인터랙티브 레슨 시작