Context API in React : everything you need to know

If we want to pass some kind of data from one component to another or from parent to child component, the one way is to pass props to other components manually.

if the structure of the component tree is gigantic then it can be tedious to pass the data to a lower component like below example.

passing props.png

we have a solution to this problem which is Context API

It helps you to keep your data in central place, so that you can access the data anywhere in the component tree without passing via props(below is the example).

context example.png

Three major terminologies involved here:

  • Context
  • Provider
  • Consumer

How to use useContext in steps:

  • Step 1
export const MyContext = createContext("Some default value");
  • Step 2 Then we will create provider.
export const MyProvider = ( )=> {
 const [count, setCount] = useState(0);
return(
<MyContext.Provider value = {[count,setCount]}>
<ComponentOne/>
<ComponentTwo/>
<MyContext.Provider/>
);
};

But how to use that data in componentOne and ComponentTwo?

  • Step 3 One way to get access to that data is to use useContext hook. And destructure the value like below.
export const Component = ()=> {
const [count, setCount] = useContext(MyContext);
const increase = ()=> {
setCount((c) => c+1);
};

return (
<div>
   <div>{count}</div>
   <button>Increase</button>
</div>
);
};