'Updating a specific field of object state in React

I am using a React functional component where I want to update only a specific field of the state and retain the other values like before. Here's the state initialization -

const[value, setValue] = React.useState({
     a: "5",
     b: "6"
});

I wish to only update value of 'a' to something else, let's say 7 (whilst retaining the same value for 'b'). Currently I am doing this -

setValue(currValue => ({
   ...currValue,
   a: "7"
}))

Is this wrong ? If yes, what's the correct way of doing it ?



Solution 1:[1]

What you are doing is correct.

That's the proper way for updating the state based on the current value of the state. It's called the functional form of the setState call.

setState((prevState) => {
  // Do something with prevState
  return newState; // Be aware to not mutate the prevState directly
});

Examples:

// Array

setState((prevState) => {
  const newState = Array.from(prevState);
  newState.push('foo');
  return newState;
});

// Object

setState((prevState) => {
  return({
    ...prevState,
    foo: 'bar'
  });
});

The main thing is that the object/array reference needs to change!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1