Learn React context by example
Passing data in React is straightforward. It is top to down, from the parent to the child component. But what when you need some data in the root component and have to pass it a few levels down? It can be messy doing it like that. That is the reason why there is context. It allows us to share values down the tree without explicitly passing them. In this post, you can find out how to use the context feature with React hooks.
As mentioned before, the context has many different use cases. For this post, I am using user data as an example. When you log in, this is the object you use in different places.
Step 1: Create a context
Creating context is simple, and for that, you have one function, createContext. This function receives only one parameter, default data. The result of this function is the context object, which contains the provider component.
Step 2: Using the provide component
Context data is available anywhere inside the context. Still, you need to wrap all the components into the provider. The provider is a component that is available to you by executing the createContext function. This component requires one prop, value. Whatever you pass in this prop is available in all components underneath it.
Step 3: Access context data
Once you create the context and wrap everything in the provider, you want to access that data. Here is the place where the React hooks come in. All you need to do is use the useContext hook and pass context to it. After that, your context data is available.
You can find code from this post in my GitHub repository.