React Context

Hyor·2022년 11월 3일
0

Context란

React 에서 Props를 사용하지 않아도 전역관리를 할 수 있게 도와줍니다.
아래 소스를 보면 "Toolbar" 컴포넌트가 사용하지 않는 prop를 받아 "ThemeButton" 컴포넌트에 전달합니다. App 안의 모든 버튼이 "theme"를 알아야 한다면 하나 하나 넘겨주는 과정은 코드를 복잡하게합니다.

class App extends React.Component {
  render() {
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton theme={props.theme} />
    </div>
  );
}

class ThemedButton extends React.Component {
  render() {
    return <Button theme={this.props.theme} />;
  }
}

여기서 Context를 사용한다면 원하는 값을 Component Tree 가장 하위요소까지 보낼 수 있습니다.
light를 기본값으로 하는 테마 context를 만든 후 Provider를 이용해 하위 트리에 "theme" 값을 보내줍니다. 아무리 깊숙히 있다하여도 모든 컴포넌트가 이 값을 읽을 수 있습니다.

그렇다면 하위 요소에서는 어떻게 Context를 받을 수 있을까요? 정답은 테마 값을 읽기 위해 contextType을 지정합니다.
React는 가장 가까이 있는 테마 Provider를 찾아 그 값을 사용할 것입니다.
아래 예시에서 현재 선택된 테마는 dark입니다.

const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}
profile
개발 노트

0개의 댓글