반응형

1. Context API란?
React의 Context API는 전역 상태(Global State) 를 관리하기 위한 도구입니다.
즉, 여러 컴포넌트가 공유해야 하는 데이터를 props로 계속 전달하지 않아도 사용할 수 있게 해줍니다.
function App() {
return <Parent />;
}
function Parent() {
return <Child user="광수" />;
}
function Child({ user }: { user: string }) {
return <GrandChild user={user} />;
}
function GrandChild({ user }: { user: string }) {
return <p>안녕하세요, {user}님!</p>;
}
위처럼 props를 계속 아래로 전달하는 구조(Prop Drilling) 는 컴포넌트가 많아질수록 불편해집니다.
2. Context Provider로 해결
React.createContext() 를 사용하면 전역 데이터 저장소를 만들 수 있습니다.
Provider는 하위 트리에 데이터를 공급(Provide) 하는 역할을 합니다.
import React, { createContext, useContext, useState, ReactNode } from "react";
// 1️⃣ Context 생성
const UserContext = createContext<{ user: string; setUser: (v: string) => void } | null>(null);
// 2️⃣ Provider 컴포넌트 정의
export const UserProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState("Guest");
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};
// 3️⃣ Context를 쉽게 사용하는 커스텀 훅
export const useUser = () => {
const context = useContext(UserContext);
if (!context) throw new Error("useUser는 UserProvider 내부에서만 사용해야 합니다!");
return context;
};
실제 사용 예제
// App.tsx
import React from "react";
import { UserProvider } from "./UserContext";
import Profile from "./Profile";
function App() {
return (
<UserProvider>
<Profile />
</UserProvider>
);
}
export default App;
// Profile.tsx
import React from "react";
import { useUser } from "./UserContext";
function Profile() {
const { user, setUser } = useUser();
return (
<div>
<h2>안녕하세요, {user}님!</h2>
<button onClick={() => setUser("홍길동")}>이름 변경</button>
</div>
);
}
export default Profile;

A conceptual 3D illustration of React Context Provider architecture — a central glowing core labeled “Provider” sending energy lines to multiple smaller nodes labeled “Components” around it, representing data flow and state sharing. Futuristic digital style, blue and white color scheme, clean UI design background, symbolizing data connection, simplicity, and reusability in React application.


반응형
'교육' 카테고리의 다른 글
| react-helmet의 기본 개념과 사용법 (0) | 2025.11.18 |
|---|---|
| 「React 18 + TypeScript + MobX 기반 구조에서 useStore 훅 설계와 스토어 계층 아키텍처 이해」 (0) | 2025.11.17 |
| "TypeScript 제네릭 기반 Form 재사용 패턴: React Hook Form과 함께하는 고급 Form 설계" (0) | 2025.11.17 |
| #007 React useMemo : 성능 최적화의 정석 (0) | 2025.11.13 |
| #005 React Context 교육자료: 장바구니 상태 관리 (0) | 2025.11.12 |