TIL35. useContext

김정현·2020년 11월 29일
1

useContext

보통 state의 이동은 한 단계씩 전달된다. state가 거쳐 가는 component가 많을수록 코드와 머릿속이 동시에 복잡해진다...
Context API는 global 하게state 값을을 관리해준다.원하는 곳에한 번에 값을 전해줄 수 있다.

  • context 객체? React.createContext(디폴트값)로 생성된다. context를 사용하면 모든 하위 컴포넌트를 일일이 통하지 않고도 원하는 값을 컴포넌트 트리 깊숙한 곳에서 사용할 수 있다.
  • context의 값은 이 Hook을 호출하는 컴포넌트에 가장 가까이에 있는 <MyContext.Provider>의 value prop에 의해 결정된다.
const value = useContext(MyContext);
const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

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

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

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

function ThemedButton() {
  const theme = useContext(ThemeContext);

  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  );
}
  • 함수 설명
  1. React.createContext(디폴트값)으로 context 객체를 만든다.
  2. 해당 context를 사용하려고 하는 컴포넌트를 <context객체명.Provider value={값}></ context객체명.Provider>로 감싼다.
  3. Provider로 감긴 컴포넌트에 물려있는 하위 컴포넌트에서는 props 명시가 없더라도 이 context를 내려 받는다.
  4. context 객체 값이 변경될 때마다 Provider에 감싼 컴포넌트와 그 하위(nested) 컴포넌트들은 새롭게 렌더가 된다.
  5. context에 담은 value를 사용하기 원하는 컴포넌트에서 useContext(context객체명)를 변수에 담고, 사용하기 원하는 태그에서 value를 사용한다.

0개의 댓글