Updating Arrays in State

Updating Arrays in State

This is the summarization of React docs that I studied recently.


Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in state.

Updating arrays without mutation

Like with objects, you should treat arrays in React state as read-only.

  • if you copy an array, you can’t mutate existing items inside of it directly. This is because copying is shallow—the new array will contain the same items as the original one
  • When updating nested state, you need to create copies from the point where you want to update, and all the way up to the top level.
  • You can use map to substitute an old item with its updated version without mutation.

Recap

  • You can put arrays into state, but you can’t change them.
  • Instead of mutating an array, create a new version of it, and update the state to it.
  • You can use the [...arr, newItem] array spread syntax to create arrays with new items.


#react #reactdocs #array #frontend

To view or add a comment, sign in

Others also viewed

Explore topics