[React] Context API

Sang Young Ha·2022년 7월 21일
post-thumbnail

What is Context API?

  • 컴포넌트 간 주고 받을수 있는 (어디서나 꺼내 쓸 수 있는) global variable 을 효과적으로 produce 할 수 있다.
  • "prop drilling"(부모 컴포넌트에서 자식의 자식의 자식으로 계속 프랍을 전달하는것) 의 대체 방안 이라고 한다. prop drilling 의 문제점은 프랍을 계속 전달 받는 컴포넌트 수가 많아지면 그걸 추적하고 유지보수 하는 것이 힘들어 지기 때문이다.

How to use context API

  • React.createContext() 만 있으면 사용 할 수 있다!
  • consumer 와 provider 을 return 한다.
  • provider 은 이름과 같이 자식에게 state 을 제공한다.
  • "store" 을 가지고 있으며 이 store 을 필요로 하는 모든 컴포넌트의 부모격이 된다.
  • consumer 은 해당 state 를 사용하는 컴포넌트를 말한다.

in code?

  • Contexts.js 라는 파일을 root 에 생성된 context 폴더에 생성한다(컨벤션이다)
import React, { createContext } from "react";
const UserContext = createContext();
  • 위와 같이 import 를 한 후, provider을 감쌀 컴포넌트를 만들어 준다.
const ConsumerProvider = ({ children }) => {
  const [name, setName] = useState("John Doe");
  const [age, setAge] = useState(1);
  const happyBirthday = () => setAge(age + 1);
  return (
    <UserContext.Provider value={{ name, age, happyBirthday }}>
      {children}
    </UserContext.Provider>
  );
};
  • state 를 consume 할 상위 order의 컴포넌트를 생성하고, export 해준다.
const withConsumer = (Child) => (props) => (
  <UserContext.Consumer>
    {(context) => <Child {...props} {...context} />}
    {/* Another option is:  {context => <Child {...props} context={context}/>}*/}
  </UserContext.Consumer>
);

export { ConsumerProvider, withConsumer };
  • 이후 사용은 app.js 에서
    <ConsumerProvider>
      <Component {...pageProps} />
      </ConsumerProvider>

나 해당 컴포넌트를 export 할때 다음과 같이 사용 할 수 있다.

export default withConsumer(Landing);

0개의 댓글