React useContext Hook

React Context provides a way to manage state globally across a component tree. It can be used in conjunction with the useState Hook to share state between deeply nested components more efficiently than using useState alone.

Tutorials dojo strip

The Challenge

State should be managed by the highest parent component in the component hierarchy that needs access to the state. To illustrate, consider a scenario where we have several nested components. The topmost component and the bottommost component both need access to the state.

Without Context, we would have to pass the state as “props” through every nested component, a process known as “prop drilling”.

Example

Passing “props” through nested components:

In this example, even though components 1-3 don’t need the state, they still have to pass it along to reach the final component.

JavaScript

Creating Context

The solution is to create a Context. To create a Context, import createContext and initialize it:

JavaScript

Next, use the Context Provider to wrap the components that need access to the state.

Context Provider

Wrap child components with the Context Provider and supply the state value:

JavaScript

Now, all components within this tree will have access to the user Context.

Using the useContext Hook

To access the Context in a child component, use the useContext Hook.

First, include useContext in your import statement:

JavaScript

Then access the user Context in any component:

JavaScript

Full Example

A complete example using React Context:

JavaScript
Tutorials dojo strip