DEV Community

Cover image for React hooks: An advanced look at converting useState to useReducer
Lyndsi Kay Williams
Lyndsi Kay Williams

Posted on

React hooks: An advanced look at converting useState to useReducer

In my previous blog, I gave a basic demonstration on how to manage state with useReducer instead of useState. In this blog, I'll dive into a more complex example.

When managing state for a form, things can get complex quickly. Take this form, for example:

basic form

To manage the form's state locally with useState, it would look something like this:

const [name, setName] = useState('')
const [title, setTitle] = useState('')
const [favoriteNumber, setFavoriteNumber] = useState('')
const [favoriteColor, setFavoriteColor] = useState('')
Enter fullscreen mode Exit fullscreen mode

This might seem manageable enough for now - but if the form needs to grow, one useState per input will turn your code into spaghetti before you know it! Let's take a look at how we can make state management more scaleable with useReducer using the same steps shown in my previous blog:

  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.

Following the steps above, we can convert our useState state to useReducer state.

1. Define an initial state and an action type:
const initialState = {
  name: 'Default name',
  title: 'Default title',
  favorite_number: '3',
  favorite_primary_color: 'red',
};

const INPUT_CHANGE = 'inputChange';
Enter fullscreen mode Exit fullscreen mode
2. Replace the useState hook with the useReducer hook:
import { useReducer } from 'react';

const FormComponent = () => {
  const [formData, setFormData] = useReducer(formReducer, 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 formReducer = (state, action) => {
  const stateCopy = { ...(state || {}) };

  switch(action.type) {
    case INPUT_CHANGE:
      return {
        ...stateCopy,
        [action.payload.name]: action.payload.value
      }

    default:
      return null;
  }
}
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 FormComponent = () => {
  const [formData, setFormData] = useReducer(formReducer, initialState);

  const internalOnchange = (type, payload) => {
    setFormData({ type, payload })
  };

  // ...

  return (
    <form>
      <input
        type="text"
        id="name"
        name="name"
        onChange={event => {
          internalOnchange(INPUT_CHANGE, {
            name: event.target.name,
            value: event.target.value,
          });
        }}
      />

    {/* ... */}

    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

Step 4 is a little more complex in this example. In order to pass the type and payload to the reducer cleanly, I've implemented an internalOnchange helper function. Now the internalOnchange can be passed into any input on the form, as shown on the name input above.

As long as the name attribute of the input matches the data you want to change, that value in state will be changed. Now the form can have unlimited inputs with no need to change the state management functionality!

...unless the form gets even more complex?? Not a problem, you can add another action to your formReducer to manage any specialized inputs. To see this form as a completed project, check it out here on Github.

I've created the example form explained above - it changes state independently by action, but I've also included an option to change the data as a whole by manipulating the entire JSON directly. This is done by passing the entire changed JSON as the payload here and using an updateData action, created here. This project will look a little different than the blog example since it's done in TypeScript, I wanted to keep things simple in this blog so I explained it in JavaScript.

I hope this blog clearly explained using useReducer to handle state instead of useState. If you have any questions or comments, I'd love to hear what you've got!

Top comments (1)

Collapse
 
brense profile image
Rense Bakker

You don't need switch statements to use reducers for forms like that, this is enough:

const initialState = {
  name: 'Default name',
  title: 'Default title',
  favorite_number: '3',
  favorite_primary_color: 'red',
}

function formReducer(prevState, nextState){
  return { ...prevState, ...nextState }
}

function FormComponent(){
  const [formData, setFormData] = useReducer(formReducer, initialState)

  return (
    <form>
      <input
        value={formData.name}
        onChange={event => setFormData({ name: event.target.value })}
      />
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode