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.
Contents
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 |
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> </> ); }
gameLists.filter(a => a.id !== game.id) game.id(this Id was we want to remove from array)
const tempList = [...list]; tempList.reverse(); setGameLists(tempList);
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!
Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…