How to store and update multiple field values in React using useReducer

If you’re like me, you probably found yourself using useState when you needed to update a single piece of state. But what if you need to store and update multiple pieces of state?

The useReducer hook allows us to update state in a reducer function, which is very similar to a reducer function in Redux.

To use a useReducer hook to update multiple pieces of state, we need to pass in an object as the first argument to the hook. This object will contain all of the different pieces of state that we want to update.

The object will look something like this:

const fieldValues = {
  field1: "value1",
  field2: "value2",
  field3: "value3"

We can then write a reducer to store and update these values:

const [fieldValues, setFieldValues] = useReducer(
    (state, newState) => ({ ...state, ...newState }),

We can then easily update multiple field values at once:

  field1: "new value of field1",
  field2: "new value of field2"

And that’s all there is to it! This is a very simple example, but you can use this same pattern to update any number of fields in your state.

5 1 vote
Article Rating
Notify of
Inline Feedbacks
View all comments