mason
mason-log.

mason

mason.

안녕하세요. mason 입니다.

react

React Context API.

createContext, Provider, prop drilling 해결, 성능, 대안 패턴

Context는 props 없이 트리 깊숙이 데이터를 전달하는 React 내장 API입니다.

📘 기본 패턴

const ThemeContext = createContext<'light' | 'dark'>('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Page />
    </ThemeContext.Provider>
  );
}

function Page() {
  const theme = useContext(ThemeContext);
}

✅ 적합한 데이터

  • theme, locale, auth session
  • 자주 안 바뀌는 전역 설정
  • prop drilling이 깊지만 updates가 드문 경우

⚡ 성능

Context Provider 값 변경과 Consumer 전파

  • Provider value 변경 → 해당 context 구독 모든 consumer 리렌더
  • 해결: context 분리 (state vs dispatch), memo, selector library (Zustand, Jotai)

🔀 대안

도구특징
Context내장, 단순, frequent update에 약함
Zustand/Jotaiatomic, selective subscribe
Redux큰 앱, middleware, devtools
URL stateshareable, bookmark

🔗 참고 자료