How to use the Context API with Hooks in React
by Aiden Oliver
If you are familiar with State in React and how you can pass it down using props, then the Context API will do you wonders.
Context makes it easier to pass state to your other components without having to pass it down using props which can be tedious at times. Using the Context API, I am going to show you how to make a component that you can use through out your whole app without any props hierarchy.
I will show you a brief example on how to pass a useState hook that can be used through out your whole project.
First, you’ll want to create a file that will hold the hooks and data that you will be using. This will be our context file where we will create our context. Import the useState and createContext functions from react and create a component called “Context” or whatever you prefer and set it equal to the createContext() function.
Create another component called ContextProvider (you can name it anything, just make sure to add Provider to the end like I did). This is where we will create our useState data. Make sure to pass in props to the useState hook.
Now, in the return area, add a tag that inherits the name of our first component we made with the createContext method and set the value equal to the variable and setter function that we created in our useState hook. Now within that tag use just created, call props.children in curly brackets and you should be good to go:
Now we can make a component that takes advantage of our context data. Within the Nav component I have imported Context from our Context.js file. Be sure to also use the useContext hook by importing it from React. Now we can use our items and setter function and instead of using useState like we normally would, we would replace it with useContext and inside the parenthesis add our Context. As you can see, I did a simple map to display all of our data from the context:
Finally, all we have to do is import our ContextProvider from our context file and make sure to add our Nav component. Make sure to wrap the main div with the ContextProvider tag and that’s it. No more passing down props!