Posted in

How to use useReducer in React?

If you’ve spent any time building React apps, you’ve probably run into the moment where state updates stop feeling straightforward. You might have a component with a dozen different state variables, each tied to a handler that updates it, and suddenly adding a new feature means chasing down three different functions to make sure nothing breaks. That’s where I come in—my company specializes in building, optimizing, and supporting reducers for teams that want to keep their React state predictable and maintainable. After years of working with developers across industries, I’ve seen firsthand how many teams struggle to switch from useState to useReducer, or how to use the hook well when they do. Today I’m breaking down exactly how to use useReducer` in React, and how custom reducers built by our team can make this tool work even better for your app. Reducer

First, let’s start with the basics: what is useReducer and when do you actually need it? Unlike useState, which lets you update state by directly setting a new value, useReducer uses a pattern called reducer state management. A reducer is a pure function that takes two inputs: the current state of your component, and an “action” that describes what change you want to make. It returns a new state, and that’s it—no side effects, no random changes, just a predictable transformation. The useReducer hook wraps this pattern, letting you access the current state and a dispatch function that you use to send actions to the reducer.

A lot of developers default to useState for every component, and that works fine for small apps with just a few state variables. But when you’re dealing with complex state: multiple sub-values (like a form with name, email, password, and error status), state that depends on previous values, or state updates that get repeated across components, useReducer becomes a game-changer. It centralizes all your state update logic in one place, making it easier to test, debug, and scale. Our team often sees teams waste hours trying to track down a weird state bug in a component with five separate useState calls—when a reducer would have made that bug obvious in minutes.

Let’s walk through the core syntax to make this concrete. The basic structure of useReducer looks like this:

First, you define your reducer function. For a simple example, let’s say we’re building a shopping cart. The state will be an array of items, and actions will be things like adding an item, removing an item, or updating the quantity.

function cartReducer(state, action) {
  switch(action.type) {
    case 'ADD_ITEM':
      // Return a new array so React knows state has changed
      return [...state, action.payload];
    case 'REMOVE_ITEM':
      return state.filter(item => item.id !== action.payload.id);
    case 'UPDATE_QUANTITY':
      return state.map(item => 
        item.id === action.payload.id 
          ? {...item, quantity: action.payload.quantity} 
          : item
      );
    default:
      // If someone sends an unknown action, return the current state
      return state;
  }
}

Notice that this reducer is a pure function: it never changes the original state array, it just returns a new one. That’s a key rule of reducers—if you mutate state directly, React won’t re-render your component, and your state updates will be inconsistent.

Next, you use the useReducer hook in your component. You pass the reducer function and an initial state, and the hook gives you the current state and the dispatch function.

import { useReducer } from 'react';

function ShoppingCart() {
  const [cart, dispatch] = useReducer(cartReducer, []);

  // Handlers that dispatch actions
  const addItem = (item) => {
    dispatch({ type: 'ADD_ITEM', payload: item });
  };

  const removeItem = (item) => {
    dispatch({ type: 'REMOVE_ITEM', payload: item });
  };

  const updateQuantity = (id, quantity) => {
    dispatch({ type: 'UPDATE_QUANTITY', payload: { id, quantity } });
  };

  // ... rest of your component
}

This is where the power becomes clear. Instead of having three separate handlers that each update state, you have one dispatch function that sends actions to a central reducer. If you need to add a new action—like clearing the entire cart—you just add a new case to your reducer, no need to rewrite handlers all over your component. For a small shopping cart, this might not feel like a huge difference, but for a component with 10 different state updates, this structure eliminates a lot of confusion.

Now, let’s talk about common pitfalls that new developers run into with useReducer, and how our team’s approach to reducers avoids these issues. The first big mistake is making reducers too complex. A reducer should handle one domain of state—our team builds reducers that are single-responsibility, so a cart reducer only handles cart state, a form reducer only handles form input, and so on. If you have a reducer that’s 500 lines long and handles 10 different state types, it becomes just as hard to maintain as a dozen useState calls. Our custom reducers are modular, so you can combine them if needed, but each one stays focused.

Another common pitfall is mutating state inside the reducer. Let’s say someone writes their REMOVE_ITEM case like this:

case 'REMOVE_ITEM':
  state.splice(state.findIndex(item => item.id === action.payload.id), 1);
  return state;

This is wrong because splice mutates the original state array. React compares the previous state and new state by reference, so it won’t notice that the array changed, and your component won’t re-render. Even worse, mutation can lead to hard-to-debug side effects—if another component is using the same cart state, you might accidentally change it without dispatching an action. Our team tests every reducer we build for immutability, so you never have to worry about these bugs.

Then there’s the issue of initial state. Sometimes developers set initial state directly in the useReducer call, but for more complex apps, you might need to compute initial state based on props or local storage. You can do that with a third argument to useReducer: the init function. For example, if you want to load saved cart items from local storage:

const init = (initialCart) => {
  const savedCart = localStorage.getItem('cart');
  return savedCart ? JSON.parse(savedCart) : initialCart;
};

const [cart, dispatch] = useReducer(cartReducer, [], init);

This keeps your initial state logic separate from your reducer, which makes it easier to test and update. Our reducers include built-in init functions for common use cases like form state, user sessions, and cart state, so you don’t have to write that logic from scratch.

Let’s also talk about when to use useReducer vs. useState. A good rule of thumb is: if you find yourself updating multiple related state variables in the same handler, or if state updates depend on complex logic (like calculating a total, or validating form inputs before updating), go with useReducer. If you’re just toggling a modal or keeping track of a single input value, useState is still fine. But even for medium complexity, useReducer saves you time long-term. Our team often recommends switching to useReducer when your component has more than three state variables, because the structure makes it easy to add new features without refactoring everything.

Another advanced feature of useReducer is being able to dispatch from other components. If you have a cart component and a product component, and you want the product component to dispatch an “add item” action, you don’t have to pass every handler down as props. You can create a context for the cart state and dispatch, so any component can access dispatch and send actions to the reducer. That pattern eliminates prop drilling, which is a huge pain point in React apps with nested components. Our team has pre-built context providers for reducers, so you can set up this pattern in minutes instead of hours.

Now, let’s talk about why our reducer services matter. A lot of developers can write a basic reducer, but building one that’s optimized for performance, tested for edge cases, and integrates smoothly with other React tools takes experience. We’ve built reducers for everything from e-commerce carts to form management systems to state for real-time dashboards, and we’ve learned how to avoid common performance issues. For example, when using useReducer with large lists, you can memoize dispatch functions to prevent unnecessary re-renders, but that can get complicated. Our team builds reducers that include memoization out of the box, so your components only re-render when the state actually changes, even for large datasets.

We also handle debugging, which is one of the biggest benefits of using a centralized reducer. When you have a bug in state, you can look at every action that was dispatched, every state update, and track exactly where things went wrong. This is a huge time-saver for developers, especially in large teams where multiple people are working on the same app. Our reducers include built-in action logging, so you can see every state change in your browser’s dev tools, no extra code needed.

Let’s address a common objection: “I heard Redux is better than useReducer for large apps.” It’s true that Redux is a full state management library, but useReducer is a built-in React hook, and for many apps, it’s all you need. Redux adds extra boilerplate and complexity that you don’t need for small to medium apps. Our company works with teams to decide when to use useReducer and when to move to Redux, and we build both reducers for useReducer and Redux slices if that’s what you need. We don’t push one solution over the other—we build what works for your specific app.

Another thing to note: when you’re testing your components, reducers are super easy to test because they’re pure functions. You can pass in a state and an action, and assert that the output is correct, no need to mount components or simulate events. Our team writes test cases for every reducer we build, so you can run those tests as part of your CI pipeline and be confident that your state updates work as expected. For example, you could write a test for your cart reducer:

test('adds an item to cart', () => {
  const initialState = [];
  const action = { type: 'ADD_ITEM', payload: { id: 1, name: 'T-Shirt', quantity: 1 } };
  const newState = cartReducer(initialState, action);
  expect(newState).toEqual([{ id: 1, name: 'T-Shirt', quantity: 1 }]);
});

This test runs in milliseconds, and if you change your reducer later, you just update the test—no messy component tests to rewrite. Our reducers come with pre-written test suites, so you don’t have to build that from scratch either.

Let’s wrap this up with a real example of how useReducer works in a full component, and how our reducers make it simpler. Imagine a user profile form that has fields for name, email, password, and a error message for invalid inputs. Instead of four separate useState calls, you’d use a form reducer:

import { useReducer } from 'react';

const initialFormState = {
  name: '',
  email: '',
  password: '',
  error: ''
};

function formReducer(state, action) {
  switch(action.type) {
    case 'UPDATE_FIELD':
      return {...state, [action.field]: action.value, error: ''};
    case 'SET_ERROR':
      return {...state, error: action.message};
    case 'RESET_FORM':
      return initialFormState;
    default:
      return state;
  }
}

function ProfileForm() {
  const [formState, dispatch] = useReducer(formReducer, initialFormState);

  const handleSubmit = (e) => {
    e.preventDefault();
    // Validate input before updating
    if (!formState.email.includes('@')) {
      dispatch({ type: 'SET_ERROR', message: 'Please enter a valid email' });
      return;
    }
    // Submit form logic here
  };

  return (
    <form onSubmit={handleSubmit}>
      {formState.error && <div className="error">{formState.error}</div>}
      <input
        type="text"
        value={formState.name}
        onChange={(e) => dispatch({ type: 'UPDATE_FIELD', field: 'name', value: e.target.value })}
        placeholder="Name"
      />
      <input
        type="email"
        value={formState.email}
        onChange={(e) => dispatch({ type: 'UPDATE_FIELD', field: 'email', value: e.target.value })}
        placeholder="Email"
      />
      <input
        type="password"
        value={formState.password}
        onChange={(e) => dispatch({ type: 'UPDATE_FIELD', field: 'password', value: e.target.value })}
        placeholder="Password"
      />
      <button type="submit">Save Profile</button>
    </form>
  );
}

This form is easy to extend—if you add a new field like “phone number”, you just add a field case to the reducer, no new state variables. If you need to add validation for the phone number, you update the handleSubmit function. Our team builds form reducers that handle all this logic, including validation, error handling, and persistence, so you can drop a pre-built form reducer into your component instead of writing it yourself.

So, when should you use useReducer? When your state logic gets complex, when you want predictable updates, when you need to test your state easily, or when you want to avoid prop drilling. And if you don’t want to build reducers from scratch, our team is here to help. We work with teams of all sizes, from startups building their first React app to enterprise teams maintaining large codebases, to build custom reducers that fit their exact needs. We handle everything from basic reducers for small components to large, scaled state management systems for entire apps, so you can focus on building features instead of debugging state bugs.

If you’re tired of messy state updates, hard-to-track bugs, and spending hours refactoring useState code, let’s talk. We can review your current React state setup, recommend the right approach (whether that’s useReducer, custom reducers, or Redux), and build the exact tools you need to make your app’s state predictable and maintainable. Get in touch with us to start the conversation about how we can help your team use useReducer effectively.

Pipe Bend References:
React Documentation: useReducer Hook
Redux Documentation: Principles of Reducers
React Beta Docs: State Management with useReducer
Kent C. Dodds: How to use React’s useReducer hook
React TypeScript Cheat Sheet: useReducer with TypeScript


Hebei Haihao Group Huadian High Pressure Pipe Fittings Co., Ltd.
As one of the most professional reducer manufacturers and suppliers in China, we are able to meet the needs of the majority of our customers. Please rest assured to wholesale high quality reducer made in China here from our factory. For price consultation, contact us.
Address: Donglin Industrial Zone, Mengcun County, Cangzhou City, Hebei Province, China
E-mail: haihaohuadian@outlook.com
WebSite: https://www.hhfittings.com/