DEV Community

SavvyShivam
SavvyShivam

Posted on

Updating Arrays in State

Updating Arrays in State

Just like Objects, State is also designed to hold Arrays in JavaScript. However, we cannot change the state of arrays directly as we did with the other JavaScript values, like numbers, strings, and booleans.
Arrays are a kind of objects hence, just like objects, arrays should not be reassigned or mutated using methods such as push(), pop(), etc.

To update an array in React we must do either of the following:

  • Create a new Array

  • Create a copy of the existing Array

Followed by setting the state of the new Array.

Adding and Replacing elements in an Array

The push() and splice() methods will mutate the array.
Instead, we use the spread syntax and map operator respectively. The spread operator allows us to create a new array with the existing elements and new items at the end.
The map operator will create a new array from the original array which will allow us to set the state to the resulting new array.

We will explain the above logic by creating a shopping list that adds and replaces elements.
Firstly we import the useState hook.

Secondly, we will define a variable named “nextID” that will store the next ID of the current item

Next, we will create two state variables, one is the currentItem that binds to the input box and contains the name of the item that the user wants to add. The other is list which is a list of Objects with an id **and a **name and represents our shopping list.

We also define an OnClick handler for the Add button. This is where the magic happens.
When the user clicks add, we set the list to […list, {id: nextID++, name: currentItem}].
This line does the following things:

  • Create a new Array with all the elements of the list and an additional item {id: nextID, name: currentItem}.

  • Increment the nextID so that it remains unique the next time an item is added.

Next, we set the currentItem to “” (to empty the input box).

Now, we write the code to render the UI. We render the heading and an input box along with the add button.
We bind the value of currentItem with the input and handleClick with the Add Items button.

We then render a < ul > tag and use the map function to render the list of items as < li > tags inside it.

We use the map function as it loops through all the elements of an array and returns a new list by applying a function on each of them.

https://codesandbox.io/s/arrays-state-nod8ij

Top comments (0)