Using useState with an object: how to update
By Flavio
Published · Updated
Tagged: React
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.
Why changing the object directly does nothing
This looks like it should work, but it doesn’t:
const [user, setUser] = useState({ name: 'Flavio', age: 40 })
function birthday() {
user.age = 41
setUser(user) // same object, no re-render
}
React compares the new state with the old one using Object.is(). You passed the same object, so for React nothing changed, and it skips the render. The screen keeps showing 40.
Create a new object instead:
setUser(user => ({ ...user, age: 41 }))
This idea is called immutability, and it’s how React notices changes.
useState replaces the object, it doesn’t merge it
If you come from class components, this.setState() merged the object you passed into the existing state. The useState setter does not merge. Whatever you pass becomes the new state:
setUser({ age: 41 }) // name is gone now
That’s why you always spread the old object first, then override the fields you want to change.
Why the updater function matters
Here I update two fields one after another, both starting from user:
setUser({ ...user, name: 'Tony' })
setUser({ ...user, age: 50 })
The second call also starts from the old user, so it overwrites the first one. The result is the old name with age 50. The name change is lost.
With the updater function, each call receives the result of the previous one:
setUser(u => ({ ...u, name: 'Tony' }))
setUser(u => ({ ...u, age: 50 }))
Now both changes are kept.
Updating a nested object
Object spread makes a shallow copy. It only copies the first level. If a property contains another object, copy that one too:
const [user, setUser] = useState({
name: 'Flavio',
address: { city: 'Rome', zip: '00100' }
})
setUser(u => ({
...u,
address: { ...u.address, city: 'Paris' }
}))
If you only wrote { ...u, city: 'Paris' }, you’d add a new city field at the top level and leave address untouched.
When objects get deeply nested, this gets tedious. You can flatten the state into several useState calls, or use the use-immer package, which lets you write draft.address.city = 'Paris' and creates the copies for you.
One change handler for a whole form
Computed property names are great with forms. Give each input a name that matches a field in the state, and use one handler for all of them:
function Profile() {
const [form, setForm] = useState({ name: '', email: '' })
function handleChange(e) {
setForm(f => ({ ...f, [e.target.name]: e.target.value }))
}
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
</form>
)
}
Removing a property
To remove a property, copy the object before deleting from the copy:
setQuizAnswers(answers => {
const nextAnswers = { ...answers }
delete nextAnswers[propertyToRemove]
return nextAnswers
})
You can also use rest destructuring, which skips the property you name:
setUser(u => {
const { age, ...rest } = u
return rest
})
Setting a property to undefined is not the same thing. The key is still there, so it still shows up in Object.keys() and in loops over the object.
Want me to talk about your product? You can sponsor this site.