Context provides a way to pass data through the component tree without having to pass props down manually at every level

For example in the above image suppose I have some data in Component A and I want to pass that to Component D then without Context we will think like passing data top-down (parent to child) via props from App component to other Child Components.

We can create a state inside the App component and passing to via props to each child and making the change from any child to that value passing back to the App component. This is something complicated to manage every time.

Context provides an easy way to share values between components without passing prop through every level.

Lets have a code for the hierarchy we discuss

Example of Context in React

In this code let’s have some data I want to pass from App Component to any child without props then Context can help you.

In App.js Component we can write a code to provide or pass data and also we need to wrap all the child Components with Provider Component

Then we can Consume the data from any child anywhere. For example here I am fetching username from the ComponentF.

So while writing code for UserContext.Consumer you can see we need to create function with argument so we will get the value with that argument.

Multiple Context.Provider Example

If we have multiple Context.Provider then it becomes very complex to manage the code.

useContext with React

useContext hook can make code easier while consuming the value

No change with Provider coding while using useContext

Related Posts

One thought on “Context in React

Leave a Reply