"컴포넌트 트리에서 데이터를 쉽게 공유"할 수 있게 하는 전역 상태 관리 도구입니다.
부모 → 자식 → 손자 → 증손자 컴포넌트로 데이터를 전달하는 경우✔ 전역적으로 사용해야 하는 데이터가 있을 때
Props Drilling 문제를 해결해야 할 때(불필요한 props가 전달되는)Context API는 3단계 과정으로 구성됩니다.
| 단계 | 설명 |
|---|---|
| 1️⃣ Context 생성 | createContext()로 새로운 Context 생성 |
| 2️⃣ Provider 생성 | Provider를 사용하여 상태를 관리하고 하위 컴포넌트에 공유 |
| 3️⃣ Consumer(사용) | useContext()를 사용하여 데이터를 가져와서 사용 |
"인기 검색어 기능"을 예제로 하나씩 설명하겠습니다.
📌 파일: PopularSearchContext.tsx
import { createContext, useContext, useState, useEffect } from 'react';
import { getPopularKeywords } from '../api/popularKeyword.api';
const PopularSearchContext = createContext<{ popularKeywords: string[] } | undefined>(undefined);
export const PopularSearchProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [popularKeywords, setPopularKeywords] = useState<string[]>([]);
useEffect(() => {
const fetchPopularKeywords = async () => {
try {
const keywords = await getPopularKeywords();
setPopularKeywords(keywords);
} catch (error) {
console.error('인기 검색어 데이터를 불러오는 중 오류 발생:', error);
}
};
fetchPopularKeywords();
}, []);
return (
<PopularSearchContext.Provider value={{ popularKeywords }}>
{children}
</PopularSearchContext.Provider>
);
};
export const usePopularSearch = () => {
const context = useContext(PopularSearchContext);
if (!context) {
throw new Error('usePopularSearch must be used within a PopularSearchProvider');
}
return context;
};
createContext<{ popularKeywords: string[] } | undefined>(undefined);
PopularSearchProvider
usePopularSearch()
📌 파일: Layout.tsx
import Footer from '../common/footer/Footer';
import Header from '../common/header/Header';
import { LayoutStyle } from './LayoutStyle';
import { PopularSearchProvider } from '../../context/PopularSearchContext';
interface LayoutProps {
children: React.ReactNode;
}
const Layout = ({ children }: LayoutProps) => {
return (
<PopularSearchProvider>
<>
<Header />
<LayoutStyle>{children}</LayoutStyle>
<Footer />
</>
</PopularSearchProvider>
);
};
export default Layout;
📌 파일: PopularSearch.tsx
import { usePopularSearch } from '../../../context/PopularSearchContext';
export const PopularSearch = () => {
const { popularKeywords } = usePopularSearch();
return (
<div>
<h3>🔥 인기 검색어</h3>
<ul>
{popularKeywords.map((keyword, index) => (
<li key={index}>{keyword}</li>
))}
</ul>
</div>
);
};
const Layout = ({ children }: LayoutProps) => {
return (
<PopularSearchProvider>
<>
<Header />
<LayoutStyle>{children}</LayoutStyle>
<Footer />
</>
</PopularSearchProvider>
);
};
PopularSearchContext가 검색어 데이터를 관리PopularSearchProvider를 Layout.tsx에서 감싸기 → 모든 페이지에서 usePopularSearch() 사용 가능