19 October 2023

You can use the spread operator (...) to add objects or merge them together. This operator allows you to copy the properties of one object into another. The code always creates a new object. In this code example of set state, we use parentheses to create an object literal, and then we use the spread operator to include all properties from prevState and add or update the error property to nameError. This way, you ensure that you return a new object with the updated state.

Source code viewer
  1. setNameInputState((prevState) => ({
  2. ...prevState,
  3. error: nameError
  4. }));
Programming Language: ECMAScript