ReactJS: Updating Arrays in State

ReactJS Updating Arrays in State

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 

import { useState } from 'react';
let nextId = 0;
export default function List()
{
    const [game, setGame] = useState('');
    const [gameLists, setGameLists] = useState([]);
    return (
        <>
            <h1>Inspiring sculptors:</h1>
            <input
                value={name}
                onChange={e => setGame(e.target.value)}
            />
            <button onClick={() => {
                gameLists.push({
                    id: nextId++,
                    name: name,
                });
            }}>Add</button>
            <ul>
                {gameLists.map(games => (
                    <li key={games.id}>{games.name}</li>
                ))}
            </ul>
        </>
     );
}

Remove from array 

gameLists.filter(a => a.id !== game.id)
game.id(this Id was we want to remove from array)

Reverse

const tempList = [...list];
tempList.reverse();
setGameLists(tempList);

Conclusion:

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!

Previous Article

11 Best Dropshipping Supplier in USA for Your Online Store

Next Article

How to Set Product Custom Attribute Set as Default in Magento 2?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨