Using the “useContext” Hook in React: A Simpler Alternative to Redux

A walkthrough on how to use this simple but powerful hook in your React application

Warren Niu
JavaScript in Plain English

--

Photo by Ferenc Almasi on Unsplash

React hooks provide our functional components with a lot more power — becoming a more preferred approach to building applications in recent times compared to class components.

The useContext hook is no different, but it’s also important to note that it operates a bit differently compared to some of the more common React hooks, such as useState and useEffect.

This week, I was given a take-home assessment to re-create the functionality and design of a popular website to calculate your NPS (Net Promoter Score).

Delighted NPS Calculator: https://delighted.com/nps-calculator

As you can see on the website, the inputs of each row are dependent on the entries of the other rows. Users input scores on the first row, which then gets grouped on the second row, and then ultimately calculated on the third row.

Based on this behavior, we can gather that we need to have a way to track state as well as update our state. While we could pass down props from our parent component or use redux for state management, this type of app screams for us to use what’s called a useContext hook.

Before we introduce the hook in our code editor, let’s quickly review what a useContext hook is.

What is useContext?

The useContext hook is an easier way for us to access data, such as our functions and state.

Let’s imagine the structure of the web application that I linked above in React. We have a parent component that contains different levels of child components inside of it.

Now, imagine passing data from the uppermost component all the way down to the last child component.

As we’re aware, we pass data from top to bottom from one component to another through what’s called props.

As you can imagine, it can get pretty messy to pass data through every single component until it reaches the component that it’s needed.

You’d have to pass that data through each and every component, through their props, until you reach the last child component. Tiresome right?

This is where Context comes to the rescue.

The React Context API allows you to easily access data at different levels of the component tree, without having to pass data down through props.

It’s a much simpler approach to state management, especially for smaller React applications when only a few of your components need access to the data.

So, let’s take a look at how we can incorporate it into our React application!

How does useContext work?

The useContext Hook provides all the same functionality you’d expect from the Context API, just packaged up into a simple-to-use hook that you can use inside functional components.

By creating a Context, it’s important to note that it provides both a consumer and a provider and we must pass down the whole context object.

We can create a Context object in React by using React.CreateContext. If we wanted to give it an initial value, we would pass it in as an argument when creating our context. If not, we can leave it blank:

Remember to import useContext from react!

Next, let’s create our wrapper component that will wrap which components we’ll give access to our data. We’ll call this TotalProvider.

We’ll also use the useState hook to create our initial state and set all of our values to an empty string, as well as a change handler to track any changes to our state.

We’ll also create a couple of custom hooks and pass in our two newly created Contexts:

As you can see in the above snippets, we’re passing in our count state to our CountContext and our change handler function to our CountUpdateContext so we can track and update any changes made to our state. We then create a couple of custom hooks so we can access our Contexts in other components.

The count variable now holds our count state, and handleChange holds our change handler

Lastly, don’t forget to wrap our components with our TotalProvider so it has access to our Contexts and our data:

We now have the flexibility to add additional Contexts to our TotalProvider and our components within it will have access to the data as we’ve already set everything up, therefore we do not have the need to keep passing down additional props or add additional layers to our Redux store.

Conclusion

While there are a few ways we can hold state in our React applications, useContext is a great approach to manage our state for smaller apps where we have a single parent component and many layers of children components.

As an alternative to passing down props each level, which can be very tiresome and messy in a large app, or setting up a redux store which can be very complex for a small application, useContext allows us to easily have our components access data and also gives us the extra flexibility to add more data without needing to pass down additional props. All the legwork is essentially done in one quick sweep!

Try it in your next project and see the benefits for yourself.

Until next time!

Sources

Upmostly: How to Use the useContext Hook in React:
https://upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react

More content at plainenglish.io

--

--

Uncovering the truths of Software Engineering one story at a time. Former Healthcare Administrator and proud dad of my Pomeranian, Nami. Based in Brooklyn, NY