Using React Context
Posted on 7th May 2020
While developing a React app you might come across a situation where you need to share a value or state between components. If the state needs to be shared between two components and they have a direct parent-child relationship, we can pass the state from the parent to the child through props. Or if we want to share the state within multiple components we might look into something like Redux.
If the state to be shared isn’t complex, Redux might be overkill as it takes some effort to setup and use. For those cases we can use React Context.
What we will be building
We will build an app that fetches and displays users from JSONPlaceholder.
The app will be divided into three parts.
- Context - Used to share the state within the app.
- Controls - The component used to change the user.
- Display - The component used to display the User data.
The Context will share any value given to it to its direct descendants.
In our case, we will need to share four sets of data.
userId- The state that holds the current User ID.
setUserId- The function that updates the
user- The state the holds the User data.
isFetching- The state that will be used to indicate if the app is currently in the middle of fetching a user so that the controls can be disabled.
To start, create the
context folder and in it create the
Next let’s create and export the context with some default values.
After that we’ll declare a Context Provider which will expose the context to its child components.
Then let’s declare the
isFetching states and pass them to the provider.
Now we’ll setup an effect to automatically update the
user state whenever the
userId state is changed.
The Display component
Next let’s create the
Display component. Create the
components folder and in it add the file
Now we can get the
user state by from the
UserContext with the
To finish off the
Display component, let’s display the User data in a table.
The Controls component
Controls component is used to change the current
To start create the
Controls.js file in the
After that, we can get
Next we can add two buttons to change the
Finally we will add a check to the buttons to disable them if the app is already fetching a user or to stop
userId from being set to value less than 1 or more than 10.
Bringing it all together
Now all that’s left to is to bring everything together in the root component.
Then we should wrap the root
div in the
UserProvider to make the context available to all components.
Finally add the
Below is a sample of the app we just built. If you think you missed something, feel free to check out the code.
If you found this post helpful please be sure to share it! 😊