How to use useReducer in React Hooks for performance optimization

Understanding 6 different useReducer use cases for React Hooks API

Daishi Kato
Crowdbotics
8 min readFeb 13, 2019

--

Introduction

React Hooks API is officially released in React 16.8.In this post, we focus especially on useReducer by introducing various use cases. Before continuing reading this tutorial, please read the official document if you haven’t. This tutorial assumes readers already have a basic understanding of hooks.

(Also, try out the Crowdbotics App Builder to instantly scaffold and deploy a React application.)

The useReducer hook is listed in Additional Hooks.

An alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method. (If you’re familiar with Redux, you already know how this works.)

Although useState is a Basic Hook and useReducer is an Additional Hook, useState is actually implemented with useReducer. This means useReducer is primitive and you can use useReducer for everything you can do with useState. Reducer is so powerful that it can apply for various use cases.

The rest of this tutorial consists of various examples. Each example shows a certain use case and we show working code.

Example01: Minimal pattern

Let’s look at the simplest example code. We mostly use the counter example throughout this tutorial.

We first define an initialState and a reducer. Note that the state here is a number, not an object. Redux users might get confused, but this is just fine. Furthermore, the action is a plain string here.

The following is a component with useReducer.

When a user clicks a button, it will dispatch an action which updates the count and the updated count will be displayed. You could define as many actions as possible in the reducer, but the limitation of this pattern is that actions are finite.

The full working code can be found below:

Example02: Action object

This example is the one that is familiar to Redux users. We use a state object and an action object.

In this example, we keep two numbers in a state. We could use a complex object for a state as long as we organize a reducer well (ref: combineReducers). Because the action in this example is an object, we can put values like action.count in addition to a type. The reducer in this example is a bit of mess, but this allows us to simplify the component as the following.

Notice there are two counters in a state, and action types are defined to update one counter out of the two.

See the full working code below:

Example03: Multiple useReducers

The previous example has two counters with a single state, which is a typical approach for global state. Because we are only working with local state, there is another way. We can use useReducer twice. Let’s look at the reducer.

The state here is a simple number instead of an object, which is the same in Example01. Note that the action here is an object, which is different from that in Example01.

The component using this reducer will be the following.

As you can see, we have two dispatch functions for each counter. We share the same reducer function for both.

The functionality is identical to that of Example02. The full working code is below.

Example04: TextInput

Let’s look at a realistic example in which multiple useReducers work well. Suppose we have a React Native-like TextInput component, and we want to store text in local state. We can use a dispatch function to update the text.

Note that the old state is just thrown away each time the reducer is called. The component using this is the following.

How simple it is. You could add some validation logic in reducer too. See the full example code below.

Example05: Context

At some point, we might want to share state between components a.k.a global state. In general, global state tends to limit component reusability, hence first consider using local state and only passing them (incl. dispatch) by props. When it doesn’t work well, Context is a rescue. If you are not familiar with Context API, check out the official document and how to use useContext.

In this example, we use the same reducer in Example03. The following is the code on how to create a context.

The function useCount is called custom hooks which can be used just like normal hooks. For more information about custom hooks, please read the official document.

The component code is the following with useCount.

As our contextValue is just the result of useReducer, we destructure the result of useCount in the same way. Note that, at this point, it’s uncertain which context is used.

Finally, here’s the code to use it.

We have two CountProviders here. It means there are two counters, even though we have only one context. The Counters inside the same CountProvider shares the state. You might need to learn how this works by running the example code and trying it.

The full working code is below.

Example06: Subscription

Context is the preferred way to share state among components, but what if we already have a shared state outside of React components. We can technically subscribe to such a shared state and update components when the shared state is updated. This pattern has limitations and React team provides a utility package: create-subscription.

Unfortunately, the utility package is not yet for React Hooks as of writing, so we do our best with hooks for now. Let’s try to reproduce the same functionality of Example05 without Context.

First, here’s a tiny custom hook to be used.

This reducer is simply to invert the previous state, ignoring the action. [1] is to return dispatch without destructuring. Next up is the main function to create a shared state and returns a custom hook.

We use a new useEffect hook. It’s a very important hook, and you should carefully read the official document to learn how it works. In useEffect, we subscribe a callback to force update the component. We also clean up the subscription when the component is unmounted.

Let us create two shared states. We use the same reducer and initialState in Example05 and Example03.

Unlike useCount in Example05, these hooks are tied to specific shared states. We then use these two hooks.

Notice the Counter component is a stateless component in common. Finally, we use these components.

By comparing this with the code in Example05, you should notice the difference. Instead of having context providers, our components and hooks in this example are already bound to shared states. The result is identical to Example05 (at least for now).

Demos

All the examples above can be accessible in StackBlitz. You can run, fork and edit as you like. Click the button below to start.

Final notes

This tutorial mainly describes useReducer with examples. Some other hooks are introduced in the examples, but intentionally useMemo (&useCallback) is left out. This hook is important for performance optimization and you should take time to learn it.

Disclaimer: The author did pay attention to correctness, but it may include some mistakes and/or bad practices.

Building A Web Or Mobile App?

Crowdbotics is the fastest way to build, launch and scale an application.

Developer? Try out the Crowdbotics App Builder to quickly scaffold and deploy apps with a variety of popular frameworks.

Busy or non-technical? Join hundreds of happy teams building software with Crowdbotics PMs and expert developers. Scope timeline and cost with Crowdbotics Managed App Development for free.

--

--