Back to all posts

useReducer, don't useState

Published 📅: ....
Last modified 📝: ....

Share this post on BlueskySee discussion on Bluesky


This blog post assumes you have a decent initial understanding of React Hooks. I highly suggest starting with the ReactJS Docs on them first.

As developers start adopting React Hooks within their applications, many will be tempted to start with useState as their state management preferences for local component state. However, I would like to try an convince you that useReducer is a better way to manage local state.

Lets start of with defining "better" in my premise from above, the definition I will use for this article will be that its:

  • Easier to manage larger state shapes
  • Easier to reason about by other developers
  • Easier to test

So lets break down each of these three points.

Easier to manage larger state shapes

As with most of this blog post, this is mostly my opinion, however because useState no longer shallowly merges state updates like it does within classes, using a reducer function gives you the developer more control over the state merging.

As an example of this expresivity that a reducer gives us, we can useReducer to implement an undo/redo state management solution:

function init(initialState) {
  return {
    past: [],
    present: initialState,
    future: [],
  };
}
function reducer(state, action) {
  const { past, future, present } = state;
  switch (action.type) {
    case 'UNDO':
      const previous = past[past.length - 1];
      const newPast = past.slice(0, past.length - 1);
      return {
        past: newPast,
        present: previous,
        future: [present, ...future],
      };
    case 'REDO':
      const next = future[0];
      const newFuture = future.slice(1);
      return {
        past: [...past, present],
        present: next,
        future: newFuture,
      };
    default:
      return state;
  }
}

Using this reducer we can keep track of a stack of states that happen in the future and in the past, allowing the user to undo and redo their actions.

This would be fairly difficult to coordinate using useState, thats not to say that its impossible but the benefit of useReducer is the explicitness of this pattern. Which leads into the second point.

Easier to reason about by other developers

Probably a topic for another blog post, but there is no such thing as a tech-only problem in web development. Frequently, you will be building features with other developers, that have a wide variety of experience different from your own.

This is mostly a more generic topic that permeates through other topics than just React Hooks, but the general take-away with the benefit of useReducer over useState is it builds on the concepts that many developers learned working with Redux within React applications. The concept of dispatching an action and having your reducer handle the state updating logic will allow these developers to more easily grasp this method of state management over useState.

One thing to note in this reasoning, is that even if you are building a project all by yourself, you can consider the future you that comes back to work on the project as another engineer.

Easier to test

If there is one general topic that I have seen the most in discussions on the original Hooks RFC, or the React repo since the 16.8 release, or even on Twitter its how developers are really confused with how to test Hooks. I think it might take developers a while to learn how best to test their hooks and components using hooks, however the beauty of the useReducer hook, is that all your business logic for updating the state can exist in a separate function that is exported separately from your component.

This separation of the state updating logic and rendering logic, allows you to author tests for the state updating separate from the component rendering tests. Using our reducer from the above snippet, we can easily test the logic for undoing and redoing actions simply by calling our reducer function from with the test using some mocked state, and an action. We don't even need to import or use react at all within our test!

test('it supports undoing the state', () => {
  const state = {
    past: [{ count: 0 }],
    present: { count: 1 },
    future: [],
  };
  const newState = reducer(state, { type: 'UNDO' });
  expect(newState.present.count).toBe(0);
});

In Summary

I don't expect to persuade most developers to only ever useReducer over useState, nor do I personally expect to only ever use the useReducer hook over useState, they both have benefits and fallbacks that depend entirely upon their use. However, I do think that useReducer when used as a replacement for complex state management happening within an old class based component or replacing a react-redux setup can be more maintainable.


Footnotes:


Tags:

Related Posts

Web Development

Quick Tip - Theme Aware Images

Published: ....

Have you ever found the need to change the image you render on a web page based on the current preferred color scheme of your theme?

Async Class Creation In JavaScript

Published: ....

Have you ever wanted to create a class in JavaScript or TypeScript but also have the initialization be async? Here's a quick tip on a pattern that I've used in the past!

Website Redesign v10

Published: ....

I recently launched a rewrite and redesign of this personal website, I figured I'd talk a bit about the changes and new features that I added along the way!

Server Side Rendering Compatible CSS Theming

Published: ....

A quick tip to implementing CSS theming that's compatible with Server Side Rendered applications!

Podcasting By Hand

Published: ....

A brief overview on how we launched The Bikeshed Podcast, including a deep dive in our recording and distribution workflows!

Quick Tip - Specific Local Module Declarations

Published: ....

A quick tip outlining how to provide specific TypeScript type definitions for a local module!

On File-System Routing Conventions

Published: ....

Some rough thoughts on building a file-system routing based web application

You're Building Software Wrong

Published: ....

Slicing software: why vertical is better than horizontal.

Single File Web Apps

Published: ....

What if you could author an entire web application in a single file?

Resetting Controlled Components in Forms

Published: ....

A quick way to handle resetting internal state in components when a parent form is submitted!

A Quick Look at Import Maps

Published: ....

A brief look at Import Maps and package.json#imports to support isomorphic JavaScript applications!

Recommended Tech Talks

Published: ....

A collection of tech talks that I regularly re-watch and also recommend to everyone!

Request for a (minimal) RSC Framework

Published: ....

Some features and functionality that I'd like within a React Server Component compatible framework.

Bluesky Tips and Tools

Published: ....

A (running) collection of Bluesky tips, tools, packages, and other misc things!

The Bookkeeping Pattern

Published: ....

A quick look at a small but powerful pattern I've been leveraging as of late!

TSLite

Published: ....

A proposal for a minimal variant of TypeScript!

Monorepo Tips and Tricks

Published: ....

Sharing a few core recommendations when working within monorepos to make your life easier!

Next.js with Deno v2

Published: ....

This is a quick post noting that Next.js should now work with Deno v2!

Don't Break the Implicit Prop Contract

Published: ....

React components have a fundamental contract that is often unstated in their implementation, and you should know about it!

A Better useSSR Implementation

Published: ....

Replace that old useState and useEffect combo for a new and better option!

My Current Dev Setup

Published: ....

A quick look at the applications and tools that I (generally) use day to day for web development!

There Is No Standard Markdown

Published: ....

There are a variety of different markdown "standards" out there, and sometimes they're not all that consistent

Abstract Your API

Published: ....

Proposing a solution for sharing core "business" logic across services!

Tip: Request and Response Headers

Published: ....

There's a common gotcha when creating Web Request and Response instances with Headers!

Using Feature Toggles to De-risk Refactors

Published: ....

Feature toggles are often underused by most software development teams, and yet offer so much value during not only feature development but also refactors

Hohoro

Published: ....

A quick introduction to my new side project, hohoro. An incremental JS/TS library build tool!

Custom Favicon Recipes

Published: ....

Two neat tricks for enhancing your site's favicon!

Corporate Sponsored OSS

Published: ....

The various risks and pitfalls of open source software run by corporations.

The Library-Docs Monorepo Template

Published: ....

A monorepo template for managing a library and documentation together.

Building Better Beacon

Published: ....

How we solved an almost show-stopping production bug, and how you can avoid it in your own projects.

Project Deep Dive: Tails

Published: ....

A(nother) deep dive into one of my recent side projects; tails - a plain and simple cocktail recipe app.

Churn Anxiety

Published: ....

When did semver major changes become so scary?

Service Monitors and Observability

Published: ....

Leveraging service monitors properly to improve service observability.

On Adopting CSS-in-JS

Published: ....

A brief recap of how Wayfair changed it's CSS approach not once but twice in the span of 5 years!

Project Deep Dive: Microfibre

Published: ....

A deep dive into one of my recent side projects; microfibre - a minimal text posting application

Pair Programming

Published: ....

Pair programming can be good sometimes - but not all the time

Suspense Plus GraphQL

Published: ....

A few thoughts on using Suspense with GraphQL to optimize application data loading

You've Launched, Now What?

Published: ....

A few thoughts on what to do after you launch a new project

Taking a Break

Published: ....

A few quick thoughts on burn out and taking a break

Managing Complex UI Component State

Published: ....

A few thoughts on managing complex UI component state within React

Understanding React 16.3 Updates

Published: ....

A quick overview of the new lifecycle methods introduced in React 16.3

CSS in JS

Published: ....

A few thoughts and patterns for using styled-jsx or other CSS-in-JS solutions

Redesign v6

Published: ....

A few thoughts on the redesign of my personal site, adopting Next.js and deploying via Now

JavaScript Weirdness

Published: ....

A few weird things about JavaScript

Calendar

Published: ....

Building a calendar web application

React