ReactHook - useContext

choi seung-i·2022년 3월 24일
0

FE로그

목록 보기
9/19
post-thumbnail

props drilling

부모가 가진 모든 데이터를 바로 밑에있는 자식컴포넌트를 거쳐 더 하위에 있는 컴포넌트에 데이터를 전달해야 할 경우, 중간에 거치는 컴포넌트들에 props를 전달해줘야하는 것
=> 필요없는 중간 컴포넌트들에도 Props를 주면 prop을 수정시에 해당 prop을 입력해준 곳들을 다시 수정해줘야 함

드릴링 해결 방법!!

useContext

  • context의 provider를 생성해서 하위컴포넌트들에 데이터를 전달

  • 만약 외부에 있는 컴포넌트에 내려주게 될 경우 export, import를 사용

  • DOM처럼 Provider로 데이터를 받아 쓸 컴포넌트들을 감싸준다

    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>
      );
    }

    => 부모 컴포넌트에서 React.createContext()를 통해 내려주고 싶은 context를 담아 ThemeContext로 넣어준다
    => .Provider value={내려줄 context} 붙여 줄 것!!!

    //Toolbar
    function Toolbar() {
      return (
        <div>
          <ThemedButton />
        </div>
      );
    }
    //TemedButton
    function ThemedButton() {
      const theme = useContext(ThemeContext);
      return (
        <button style={{ background: theme.background, color: theme.foreground }}>
          I am styled by theme context!
        </button>
      );
    }

    => ThemeContext를 사용해 줄 컴포넌트 안에서 useContext()를 사용하면 된다.


    ---

공부하며 정리&기록하는 ._. 씅로그

profile
Front-end

0개의 댓글