anott 2022. 6. 17. 14:25
https://ko.reactjs.org/docs/context.html를 읽고 정리한 글입니다
https://velog.io/@velopert/react-context-tutorial도 함께 읽었습니다

 

  • context를 이용하면 props 없이 컴포넌트 트리 전체에 데이터 제공 가능
  • context는 global 데이터에 사용 (예 : 로그인 여부, 테마, 언어 등)
  • context를 이용하면 컴포넌트 재사용에 어려워지므로 필요할 경우에만 사용할 것 ⇒ 컴포넌트 합성이 더 좋은 방법일 수 있다
// 기본값이 light인  ThemeContext 생성
const ThemeContext = React.createContext('light');

// 로그인한 유저 정보를 담는 UserContext 생성
// displayName를 이용하여 문자열 속성 설정 가능
const UserContext = React.createContext({
  name: 'Guest',
});

class App extends React.Component {
  render() {
    const {signedInUser, theme} = this.props;

    // context 초기값을 제공하는 App 컴포넌트
    return (
      <ThemeContext.Provider value={theme}>
        <UserContext.Provider value={signedInUser}>
          <Layout />
        </UserContext.Provider>
      </ThemeContext.Provider>
    );
  }
}

function Layout() {
  return (
    <div>
      <Sidebar />
      <Content />
    </div>
  );
}

// 여러 context의 값을 받는 컴포넌트
function Content() {
  return (
    <ThemeContext.Consumer>
      {theme => (
        <UserContext.Consumer>
          {user => (
            <ProfilePage user={user} theme={theme} />
          )}
        </UserContext.Consumer>
      )}
    </ThemeContext.Consumer>
  );
}
  • 불필요하게 하위 컴포넌트가 렌더링되지 않도록 값을 부모의 state로 끌어올리기
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: {something: 'something'},
    };
  }

  render() {
    return (
      <MyContext.Provider value={this.state.value}>
        <Toolbar />
      </MyContext.Provider>
    );
  }
}

 


스터디를 통해 받은 질문

Q) context란 무엇이고 왜 사용하며, 언제 사용하는 것이 좋을까요?
A) context란 리액트 컴포넌트에서 Props를 사용하지 않고 컴포넌트 트리 전체에 데이터 제공하는 방법입니다. props로 값을 계속 내려줄 경우 유지보수가 어렵고 props 추적이 어렵기 때문에 context로 쉽게 관리할 수 있습니다. context의 사용예시에는 언어, 테마 등이 있습니다.

Q) Context api가 redux, recoil과 같은 전역상태관리 라이브러리를 대체할 수 없는 이유가 무엇일까요? 대체할수 없다면 어떠한 상황에서 사용해야 비교적 효율적일까요?
A) 리덕스 등은 컴포넌트에서 해당 값이 바뀔 때만 리렌더링이 되지만 Context는 이런 성능 최적화가 없으므로 context api는 전역상태관리 라이브러리를 대체할 수 없습니다. Context는 단순하게 prop-drilling을 피하는 경우에만 사용하는 것이 효율적입니다.