Using useState with objects: how to update

When the state variable defined with useState is an object with the properties you want to add/update, how to update it is a bit confusing.

You can't just update the object, otherwise the component will not be re-rendered.

One pattern I found involves creating a temporary object with one attribute and using object destructuring to create a new object from the two existing objects:

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

const updatedValue = {} updatedValue[quizEntryIndex] = answerIndex setQuizAnswers({ …quizAnswers, …updatedValue })

The same technique can be used to delete attributes:

const copyOfObject = { ...quizAnswers }
delete copyOfObject['propertyToRemove']

setQuizAnswers({ …copyOfObject })

Download mine for freeResponse Handbook

More response tutorials: