ReactJS

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!

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

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ? with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket ?.

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

3 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago