DEV Community

Praveen Saboji
Praveen Saboji

Posted on

Why we need Context API - ReactJs

We all heard new feature in ReactJS which is Context API, when we hear this thing we get into a conclusion that what the hell is this, but it's pretty easy to understand.

Why we need Context API ?

Whenever we have props needs to be sent to each and every child of parent component we do it by sending prop name assigning it to prop value.

like this in render
for eg :

return (<
<Mycomponent props1={1} p2={2} ...
<Mycomponent2 props1={1} p2={2} ...
...
</>)
Enter fullscreen mode Exit fullscreen mode

But when we use Context API we need not send every prop with its value on each child component.

When to Use Context API :
When we get into a situation where we need to send all the props of parent to its child deep down till last child

How to use this ?
There are two things in Context API

1.Provider - This should be used in Parent component, for every child component this acts as value provider, and every component acts as consumer to this Provider.

Syntax :

<Provider value={state}>
{children}
</Provider>
Enter fullscreen mode Exit fullscreen mode
  1. Consumer - This should be used in every child component to access global context values.

Syntax :

<Consumer>
{value => /* render something based on the context value */}
</Consumer>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)