Getting started with React Context API
Whenever you're utilizing a component architecture, as your application grows, the ability to share state amongst different components will inevitably become an issue.
Let's pretend we had an app with the following architecture, each circle representing a different component.
The state should be held by the highest parent component in the stack that requires access to the state.
To illustrate, we have many nested components. The components at the top and bottom of the stack need access to the state.
To do this without Context, we will need to pass the state as "props" through each nested component. This is called "prop drilling".
This works, and most of the time it's the right solution. However, there are times when passing props through intermediate components can become overly redundant or downright unmanageable. Take a tool like React Router for example. React Router needs to have the ability to pass routing props to any component in the component tree, regardless of how deeply nested the components are. Because this is such a significant problem, React comes with a built-in API to solve it called Context.
Context provides a way to pass data through the component tree without having to pass props down manually at every level. - The React Docs
The Context API
There are four steps to using React context:
Create context using the createContext method.
Take your created context and wrap the context provider around your component tree.
Put any value you like on your context provider using the value prop.
Read that value within any component by using the context consumer.
To create context, you must Import createContext and initialize it:
Next, we'll use the Context Provider to wrap the tree of components that need the state Context.
Context Provider
Now, all components in this tree will have access to the user Context.
Use the useContext Hook
In order to use the Context in a child component, we need to access it using the useContext Hook.
First, include the useContext in the import statement and then you can access the user Context in all components:
Conclusion
The main takeaways from this article include the following:
The React Context API is designed for prop drilling
If you use Context for global state management, use it sparingly
If you can’t be prudent with Context, try Redux
Redux can be used independently of React
Redux is not the only state management tool available
In this article, we reviewed what the React Context API is, when we should use it to avoid prop drilling, and how we can use Context most effectively. We also cleared up some misconceptions surrounding the React Context API and Redux. I hope you enjoyed this tutorial!