220328 TIL

leevshan·2022년 3월 28일
0

How to communicate without using downward-only props

Context API

How to use it? First, create a context using React.createContext().
Then this context on the top component allows all the other child components to use the same variable or state.
In App.js, make a <SomeContext.Provider> component and set the value prop as the variable or state you want to manage in other components.

How to get the context data from child components

Use useContext() hook to get the data from Context API.

import { useContext } from "react";
import PersonContext from "../contexts/PersonContext"; //The context file that contains React.createContext()

export default function ContextExample() {
  const persons = useContext(PersonContext);

  return (
    <ul>
      {persons.map((person) => {
        <li>{person.name}</li>;
      })}
    </ul>
  );
}
profile
Planby 개발자

0개의 댓글