728x90
300x250
SMALL
Context API란?
React에서 컴포넌트 간 상태를 공유할 때 가장 일반적인 방법은 props를 사용하는 것이다. 하지만 컴포넌트 구조가 깊어지면 Props Drilling(중첩된 컴포넌트에 계속해서 props를 전달하는 문제)이 발생할 수 있다.
이를 해결하기 위해 Context API를 사용하면, 부모 → 자식 → 손자 컴포넌트로 직접 props를 전달하지 않고 전역으로 상태를 공유할 수 있다.
Context API의 역할
- 공통 상태를 한 곳에 저장
- Provider를 통해 트리 구조의 모든 컴포넌트에 데이터 제공
- 데이터가 필요한 하위 컴포넌트에서 useContext를 통해 쉽게 접근
Context API의 핵심 개념
- Context 생성 : createContext()를 사용해 컨텍스트를 만든다.
- Provider : Context.Provider로 데이터를 공급한다.
- Consumer: useContext(Context)를 이용해 데이터를 가져온다.
Context API 사용 예제
import React, { createContext, useState, useContext } from "react";
// 1. Context 생성
const ThemeContext = createContext();
// 2. Provider 컴포넌트 만들기
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
// 3. Consumer 사용
const ThemedComponent = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === "light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff", padding: "20px" }}>
<p>현재 테마: {theme}</p>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>테마 변경</button>
</div>
);
};
// 사용 예시
const App = () => (
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
export default App;
사용 예제 분석
const ThemeContext = createContext();
React.createContext()
- 새로운 Context를 생성
- 여기서 ThemeContext는 우리가 데이터를 공유할 컨테이너이다.
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
SharedStateContext.Provider
- Provider는 Context의 데이터를 전달하는 역할을 한다.
- value라는 prop을 통해 전달할 데이터를 정의한다.여기서는 {theme, setTheme} 객체를 전달
- 이제 Provider로 감싸진 모든 하위 컴포넌트에서 이 데이터를 사용할 수 있다.
const ThemedComponent = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === "light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff", padding: "20px" }}>
<p>현재 테마: {theme}</p>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>테마 변경</button>
</div>
);
};
React.useContext(SharedStateContext)
- useContext 훅을 사용하면 Context에서 제공하는 데이터를 가져올 수 있다.
- 여기서 theme는 부모 컴포넌트의 상태 값이고, setTheme는 상태를 업데이트하는 함수이다.
const App = () => (
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
Provider를 App에서 감싸기
- ThemeProvider가 ThemedComponent 컴포넌트를 감싸므로, ThemedComponent는 theme와 setTheme를 사용 가능
- ThemedComponent가 직접 ThemeProvider에서 theme 상태를 가져오므로 props Drilling이 사라짐
Context API 사용 이점
- props없이 전역적으로 상태 공유
- Redux보다 간단하게 상태 관리 가능
- 코드 구조가 깔끔해지고 유지보수가 쉬움
728x90
반응형
LIST
'Front-end > React' 카테고리의 다른 글
Redux 완벽 가이드 : 개념, 사용법, 예제코드 (0) | 2025.02.08 |
---|---|
전역 상태 관리 필수 개념과 React에서 최적 솔루션 (0) | 2025.02.06 |
React에서 컴포넌트 간 데이터 공유하기 - Shared State (0) | 2025.02.05 |
Props Drilling 문제란? (0) | 2025.02.04 |
React에서 useState를 활용한 간단한 회원가입 폼 만들기 (0) | 2025.02.03 |
댓글