Hello React Friends,

Today we will learn about updating arrays in React state. 

To update an array stored in state, you need to create a new blank one or copy of the existing one and then set the state to use the new array.

Updating arrays without mutation 

In React, you should treat arrays as read-only, which means you cannot reassign items inside an array like arr[0] = ‘bird’ or methods such as push() and pop() which mutate the array.

So whenever you want to update an array, you can pass a new array to your state setting function. For that, you can create a new array from your state’s original array by calling its non-mutating methods like filter() and map() and then set your state to the resulting new array.

When dealing with arrays inside React state, which methods you must avoid and which methods you must prefer are stated in the below table:

avoid (mutates the array) prefer (returns a new array)
Adding push, unshift concat, […arr] spread syntax
Removing pop, shift, splice filter, slice
Replacing splice, arr[i] = … assignment Map
Sorting reverse, sort copy the array first

To add item in array 

Remove from array 



This was about updating arrays in React state. If you have any doubts, share them with me through the comment section. Share this tutorial with your friends to help them learn about updating arrays in React. 

Happy Coding!

Click to rate this post!
[Total: 3 Average: 5]