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