DEV Community

Cheat Sheet for Updating Objects and Arrays in React State

Andrew Lee on May 04, 2020

If we want to use arrays or objects in our React state, we have to create a copy of the value before modifying it. This is a cheat sheet on how to ...
Collapse
 
arunkumar413 profile image
Arun Kumar •

Can you also add how to update array of objects

Collapse
 
tombohub profile image
tombohub •

I agree

Collapse
 
andyrewlee profile image
Andrew Lee •
Collapse
 
93alan profile image
Alan Montgomery •

This is a brilliant little recap for objects and arrays. Nicely done

Collapse
 
perpetualwar profile image
Srđan Međo • • Edited

For deleting key and value from object I prefer rest operator:

const handleRemove = (todo) => {
  const {[todo]: filteredOutValue, ...newTodos} = todos;
  setTodos(newTodos)
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
viktorms profile image
ViktorMS •

Signed up just to comment. This is so well set up and explained.

Most people would just put in the one-liners without explaining what they are doing at all.

🤙

Collapse
 
chamabreu profile image
Jan Manuel Brenner • • Edited

Edit:
Thanks for this cheatsheet, nice to have it open when fighting with array states.

Mh, i learned to always get the old state like (dont focus on typos, just sketching):
const handleAdd = (todo) => {
setTodos((oldTodos) => {
return [...oldTodos, todo]
})
}

Why you dont use this?
Or is this approach only needed, if the new value depends on the old one?

Collapse
 
hkiepe profile image
Henrik Kiepe •

would also be curious about the answer - but i think your approach is not a bad approach - just different. Why the author didnt took this into account would be inetersting ...

Collapse
 
krm218 profile image
Ken Mau •

Great article and recap : P

Collapse
 
walidzhani profile image
Walid Zhy7 •

Magnifico hermano <3

Collapse
 
jakeborromeo profile image
Jake Borromeo •

In this snippet, the 'id' property is in brackets. Is this React syntax or some type of destructuring?

const handleAdd = (todo) => {
setTodos({...todos, [todo.id]: todo});
}

Collapse
 
ace540i profile image
Michael Darretta •

isn't this mutation?

const newTodos = [...todos];
newTodos[index] = todo;

Collapse
 
brianl09 profile image
brianL09 •

The spread operator [...] creates a shallow copy and thus doesn't mutate the original state directly.