DEV Community

Cover image for React hooks: How to convert useState to useReducer
Lyndsi Kay Williams
Lyndsi Kay Williams

Posted on

React hooks: How to convert useState to useReducer

useState and useReducer are both React hooks that allow you to manage state in your components. useState is a simpler hook that allows you to manage a single piece of state, while useReducer is more powerful and allows you to manage more complex state that may have multiple values and require more sophisticated updates.

To convert from useState to useReducer, you can follow these general steps:

  1. Define an initial state and an action type.
  2. Replace the useState hook with the useReducer hook.
  3. Create a reducer function that takes a state and an action and returns a new state.
  4. Update the component to use the new state and dispatch functions returned by the useReducer hook, which should have the reducer and initial state passed in.

Here is a basic example of how to convert a component that uses useState to manage a single piece of state. Start with a Counter component:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

To convert this to use useReducer, we can follow the steps outlined above:

1. Define an initial state and an action type:
const initialState = { count: 0 };
const INCREMENT = 'increment';
Enter fullscreen mode Exit fullscreen mode
2. Replace the useState hook with a useReducer hook:
import React, { useReducer } from 'react';

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  // ...
}
Enter fullscreen mode Exit fullscreen mode
3. Create a reducer function that takes a state and an action and returns a new state:
const reducer = (state, action) => {
  switch (action.type) {
    case INCREMENT:
      return { count: state.count + 1 };
    default:
      throw new Error();
  }
}
Enter fullscreen mode Exit fullscreen mode
4. Update the component to use the new state and dispatch functions returned by the useReducer hook, which should have the reducer and initial state passed in:
const Counter = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  const increment = () => {
    dispatch({ type: INCREMENT });
  };

  return (
    <>
      <p>Count: {state.count}</p>
      <button onClick={increment}>Increment</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

In step 4, the dispatch function is used to send an action to the reducer function. The reducer function then returns a new state based on the action type. The component is also updated to use state.count instead of the count variable previously returned by useState.

In this simple example, useReducer doesn't bring many benefits over useState. But in general, as your components grow in complexity, useReducer provides a more powerful and flexible way to manage state - especially when you have more complex state that require multiple values and more sophisticated updates.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay