Context API

김상현·2020년 6월 23일
0

React

목록 보기
11/16

Context API란?

주로 어플리케이션에서 전역적으로 데이터가 사용되야 할 때 사용한다. 여러 컴포넌트를 거쳐서 값을 전달하는 것이 아니라 Context를 통해서 원하는 값이나 함수를 전달할 수 있따.


  • Context는 createContext 함수를 사용해서 만들며, 함수를 호출하면 Provider와 Consumer라는 컴포넌트들이 반환된다. Provider는 Context를 이용해 전달할 값을 설정하고, Consumer는 전달할 값을 전달할 때 사용된다.
const Context = createContext();

const { Provider, Consumer } = Context;

const SampleProvider = ({ children }) => {
  const [value, setValue] = useState("Hello");
  return <Provider value={value}>{children}</Provider>;
};

const Lower = () => <Consumer>{(value) => <div>{value}</div>}</Consumer>;
const Upper = () => <Lower />;

const App = () => {
  return (
    <SampleProvider>
      <Upper />
    </SampleProvider>
  );
};

  • Context가 여러 개일때는 배열의 내장함수 reduce와 createElement를 활용한다.
const AppProvier = ({contexts, children}) => contexts.reduce((prev, context) => React.createElement(context, { children: prev }), children);

const App = () => {
  return (
    <AppProvider contexts={[Provider1, Provider2]}>
    <Component />
    </AppProvider>
  )
}                                       

useContext

  • Consumer 대신 사용하는 Hook이며 context 객체를 받아 그 context의 현재 값을 반환한다.context의 현재 값은 Hook을 호출하는 컴포넌트에 가장 가까이에 있는 Provider의 value prop에 의해 결정된다.
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>
  );
}

0개의 댓글