React _ Context API

LOOPY·2021년 8월 31일
post-thumbnail
  • context 이용하면 단계마다 일일이 props 넘겨주지 않고도 컴포넌트 트리 전체에 데이터 제공 가능
  • 데이터 set하는 가장 상위 컴포넌트: provider
    데이터 get하는 하위 컴포넌트: consumer / (class에서) this.context / (function에서) useContext

1. 데이터 set

  • context 생성 -> provider 사용 -> value 사용
// ./src/context/PersonContext.js

const PersonContext = React.createContext();

export default PersonContext;
// index.js
const persons = [
  {id: 0, name: 'Mark', age: 39},
  {id: 1, name: 'Hanna', age: 28}
];

ReactDom.render(
  <React.StrictMode>
    <PersonContext.Provider value={persons}> // 이제 하위 component에서 persons 사용 가능
      <App />
    </PersonContext.Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

2-(1). 데이터 get _ Consumer

  • funciton, class 상관X
  • context 가져오기 -> consumer 사용 -> value 사용
  • Consumer의 내용으로 함수 넣어주기
// ./components/Example1.jsx
export default function Example1(){
  return(
    <PersonContext.Consumer>
      {(persons) => (
        <ul>
          {persons.map(person => (
            <li>{person.name}</li>
          ))}
        </ul>
      )}
    </PersonContext.Consumer>
  );
}

2-(2) 데이터 get _ Class

  • static contextType에 context 설정 -> this.context 접근
// ./components/Example2.jsx
export default class Example2 extends React.Component{
  
  static contextType = PersonContext;

  render(){
    const persons = this.context;
    return(
      <ul>
        {persons.map(person => (
          <li>{person.name}</li>
        ))}
      </ul>
  };
}

2-(3). 데이터 get _ Function

  • useContext 사용해 context를 인자로 호출 -> useContext의 리턴값이 value
// ./components/Example3.jsx
export default function Example3(){
  
  const persons = useContext(PersonContext);

  return(
    <ul>
      {persons.map(person => (
        <li>{person.name}</li>
      ))}
    </ul>
  );
}

👉🏻 이거 가장 많이 사용!!!

profile
2년차 프론트엔드 개발자의 소소한 기록을 담습니다 :-)

0개의 댓글