React Context API

henry·2025년 2월 25일

🚀 1. React Context API란?

📌 개념

"컴포넌트 트리에서 데이터를 쉽게 공유"할 수 있게 하는 전역 상태 관리 도구입니다.


📌 기존 문제: Props Drilling

  • 부모자식손자증손자 컴포넌트로 데이터를 전달하는 경우
  • 중간 단계에서 필요하지 않은 컴포넌트도 props를 받아야 하는 문제가 발생함.
  • Context API를 사용하면 중간 단계를 거치지 않고 바로 데이터를 사용할 수 있음.

📌 언제 Context API를 사용할까?

✔ 전역적으로 사용해야 하는 데이터가 있을 때

  • 사용자 인증 정보 (로그인 상태)
  • 테마 설정 (다크/라이트 모드)
  • 인기 검색어 데이터 관리 (이번 프로젝트에서 사용)
  • Props Drilling 문제를 해결해야 할 때(불필요한 props가 전달되는)


🚀 2. React Context API 동작 원리

Context API는 3단계 과정으로 구성됩니다.

단계설명
1️⃣ Context 생성createContext()로 새로운 Context 생성
2️⃣ Provider 생성Provider를 사용하여 상태를 관리하고 하위 컴포넌트에 공유
3️⃣ Consumer(사용)useContext()를 사용하여 데이터를 가져와서 사용


🚀 3. Context API 사용법 (실제 구현 코드 포함)

"인기 검색어 기능"을 예제로 하나씩 설명하겠습니다.


1️⃣ Context 생성 (createContext())


📌 파일: 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;
};

✅ 설명:

  1. createContext<{ popularKeywords: string[] } | undefined>(undefined);

    • 인기 검색어를 관리하는 전역 Context 생성
    • { popularKeywords: string[] } → 검색어 목록을 저장하는 타입
    • undefined 허용 → Provider 없이 사용할 경우 예외 처리 가능
  2. PopularSearchProvider

    • useState와 useEffect를 사용하여 인기 검색어 상태 관리
    • 백엔드에서 데이터를 가져와서 (getPopularKeywords()) Context에 저장
  3. usePopularSearch()

    • useContext(PopularSearchContext)를 통해 Context에 저장된 데이터 사용
    • Provider 없이 사용 시 에러 발생하도록 예외 처리 (throw new Error(...))

2️⃣ Provider 설정


📌 파일: 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;

✅ 설명:

  • PopularSearchProvider를 Layout에서 감싸기 → 모든 페이지에서 usePopularSearch() 사용 가능
  • children을 감싸고 있으므로 헤더(Header.tsx)에서도 Context 값을 사용할 수 있음
### 3️⃣ Context 값 사용 (useContext())

📌 파일: 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>
   );
};

✅ 설명:

  • usePopularSearch()를 사용하여 popularKeywords 값을 가져옴
  • 검색어 목록을 화면에 출력

Layout.tsx

const Layout = ({ children }: LayoutProps) => {
   return (
      <PopularSearchProvider>
         <>
            <Header />
            <LayoutStyle>{children}</LayoutStyle>
            <Footer />
         </>
      </PopularSearchProvider>
   );
};

🚀 4. Context API 적용 결과

  • 1️⃣ PopularSearchContext가 검색어 데이터를 관리
  • 2️⃣ PopularSearchProviderLayout.tsx에서 감싸기 → 모든 페이지에서 usePopularSearch() 사용 가능
  • 3️⃣ usePopularSearch()를 사용하여 PopularSearch.tsx에서 데이터 사용
  • 4️⃣ getPopularKeywords() API를 호출하여 인기 검색어를 DB에서 가져옴

0개의 댓글