4

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 ?

coolest-duck
  • 105
  • 1
  • 1
  • 10

1 Answers1

6

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!

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336