Context is one those features of react that most of the developers ( including myself ) don’t get to use a lot in their regular day to day react projects. Because of that exact reason I never really tried to understand the React Context API. Recently React was updated and some new features were included in it. Among the other features one thing caught my attention and that an updated React Context API. So I finally decided to read up on the Context API.
React Context API is actually very useful in certain use cases where you want to pass props to child components deep in the components hierarchy.
Using Context in react applications involves three steps.
- Creating Context
- Providing Created Context to Components
- Accessing Context from the Child Components
Creating context is really simple, All you have to do is call
createContext method on
createContext method accepts the default value of whatever you want to store. Value passed to
createContext could be of any type i.e. string, number, array or object. In our case we are storing an object with a key color in it.
You can read more about createContext on official react website
Providing Created Context to Components
createContext returns to us an object, and in that object we get our
Provider component that we will use the context in our application. Here is how we do it.
Accessing Context from the Child Components
Now that we have created the context and used the Provider component provided by the created context to wrap our root component, It is time to actually use the values provided by the context that we have created in a child component without passing the value in the props of that component. We will use a component called
Child components looks like this
To use the context in the child component we need to set the contextType property of our component to the context that we created. Here is how we do it