Using useState with an object: how to update

By

Learn how to update an object in React useState by creating a new object with the spread operator so the component rerenders, and how to remove a property.

~~~

When you store an object in React state, treat it as read-only.

Do not change a property on the existing object. Create a new object and pass it to the state setter.

Suppose we store quiz answers by question index:

const [quizAnswers, setQuizAnswers] = useState({})

You can update one answer with object spread and a computed property name:

setQuizAnswers(answers => ({
  ...answers,
  [quizEntryIndex]: answerIndex
}))

The function receives the latest state value. This matters when React queues multiple updates before rendering again.

To remove a property, copy the object before deleting from the copy:

setQuizAnswers(answers => {
  const nextAnswers = { ...answers }
  delete nextAnswers[propertyToRemove]

  return nextAnswers
})

Object spread makes a shallow copy. If the property contains another object, copy that nested object too before changing it.

Tagged: React ยท All topics
~~~

Related posts about react: