React Context 파헤치기

옹치키·2021년 11월 18일
0

React

목록 보기
3/8
post-thumbnail

서론

Redux에 전유물로 보였던 '전역 상태 관리' 하지만, 엄격한 Flux 패턴을 따르며, 무거운 써드 파트 라이브러리인 Redux에 대응하여 보다 가볍고 유연한 Mobx, Recoil과 같은 다른 라이브러리들이 나타나고 발전했습니다.

React 진영도 Context를 통해 기능을 제공하고 있었으나, 기존 Legacy Context 는 사용해보니 여러 문제가 있었습니다. 현재는 개선된 React Context를 제공하고 있으며 이번 포스팅에서 사용법을 파헤쳐 보겠습니다.


목표

  • React Context 파헤치기

1. Context(?)

  • 컴포넌트 트리안에서 전역적으로 볼 수 있는 데이터를 공유

주의사항

  • 여러 레벨을 거쳐서 Props 데이터를 주는 것이 불 필요하다는 이유로 Context를 사용하기 보다 컴포넌트 합성을 권유한다.
  • 모든 하위 컴포넌트들에게 공통적으로 전달되는 요소를 전역적으로 관리하는것을 추천한다 (Locale, Theme, Data Cache)

2. Context 문법

2-1) CreateContext

 export const ThemeContext = React.createContext(defaultValue);
  • Context 객체 생성
  • defaultValue : Provider에서 넘겨주는 value가 없을시, 기본으로 넘겨주고자 하는 데이터

2-2) Context.Provider

import ThemeContext from './theme-context';

<ThemeContext.Provider value={/* value */}>
  {/* ...Components */}
</ThemeContext.Provider>
  • 컴포넌트를 구독하고 있는 하위 컴포넌트들에게 변화를 알림
  • 즉, Provider 하위에 있는 컴포넌트만이 해당 Context에 변화를 감지할 수 있다.
  • Provider 전파는 shouldComponentUpdate 전파(X)

2-3) Context.Consumer

function Content() {
  return (
    <ThemeContext.Consumer>
      {theme => (
        <UserContext.Consumer>
          {user => (
            <ProfilePage user={user} theme={theme} />
          )}
        </UserContext.Consumer>
      )}
    </ThemeContext.Consumer>
  );
}
  • 여러 Context를 반환 받을 수 있는 콜백 함수 제공

2-4) Context.displayName

const MyContext = React.createContext(/* some value */);
MyContext.displayName = 'MyDisplayName';

<MyContext.Provider> // "MyDisplayName.Provider" in DevTools
<MyContext.Consumer> // "MyDisplayName.Consumer" in DevTools
  • Context 객체에게 이름을 부여함으로서, 개발자 도구에서 컨택스트를 확인할 수 있다.

3. 사용예제


출처

React Context

profile
잊지 않기 위해 기록하는 프론트엔드 엔지니어입니다.

0개의 댓글