Add and remove array items immutably
Add and remove without editing the old array
A cart can store one array of item records with unique IDs. To append an item, create a new array; to remove one, keep the items whose IDs do not match. Use a functional setter when the new list depends on the pending list.
import { useState } from 'react';
function addProduct(items, product) { if (items.some(item => item.id === product.id)) return items; return [...items, { ...product }];}function removeProduct(items, id) { return items.filter(item => item.id !== id);}
export default function App() { const [items, setItems] = useState([{ id: 'mug', name: 'Mug', quantity: 2 }]); const hasTray = items.some(item => item.id === 'tray'); return <main><h1>Cart</h1> <button type="button" disabled={hasTray} onClick={() => setItems(old => addProduct(old, { id: 'tray', name: 'Tray', quantity: 1 }))}>Add tray</button> {items.length === 0 ? <p>Cart is empty</p> : <ul>{items.map(item => <li key={item.id}>{item.name}: {item.quantity}{' '} <button type="button" onClick={() => setItems(old => removeProduct(old, item.id))}> Remove {item.name} </button></li>)}</ul>} </main>;}The cart starts with two mugs. Add tray adds one distinct row and disables that button until the tray is removed. Removing the final row reveals the empty message. some checks whether an item exists; filter produces a new array containing only retained rows. This example uses a fixed local product catalog, so IDs are unique by design. The helper also prevents duplicate IDs if multiple updates are queued.
Replace only the edited item
import { useState } from 'react';
function setQuantity(items, id, quantity) { return items.map(item => item.id === id ? { ...item, quantity } : item);}
export default function App() { const [items, setItems] = useState([ { id: 'mug', name: 'Mug', quantity: 2 }, { id: 'tray', name: 'Tray', quantity: 1 } ]); return <main><h1>Cart quantities</h1><ul>{items.map(item => <li key={item.id}>{item.name}: {item.quantity}{' '} <button type="button" onClick={() => setItems(old => setQuantity(old, item.id, 0))}> Set {item.name} quantity to zero </button></li>)}</ul></main>;}Setting Mug to zero preserves its row and leaves Tray at one. Zero is a valid quantity in this demonstration; removal is a separate action. map creates an array, and the matching object is replaced. Other records keep their identity. The helper assumes unique IDs and a validated nonnegative whole-number quantity; the button supplies zero. A copied array alone would still share its item objects.
Sort a copy
import { useState } from 'react';
export default function App() { const [items] = useState([{ id: 'tray', name: 'Tray' }, { id: 'mug', name: 'Mug' }]); const [sorted, setSorted] = useState(false); const visible = sorted ? [...items].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) : items; return <main><h1>Products</h1><button type="button" aria-pressed={sorted} onClick={() => setSorted(s => !s)}>Alphabetical order</button> <ul>{visible.map(item => <li key={item.id}>{item.name}</li>)}</ul> </main>;}The first order is Tray, Mug. Activate the toggle to see Mug, Tray, and activate it again to restore the initial order. sort changes its receiver; the spread makes that receiver a separate array. The comparison is simple code-point-based ordering for these ASCII names, not locale-aware sorting. Avoid push, splice and direct index writes on stored arrays. Copying is not a license to modify shared nested records.
Practice
Write a helper that marks the item with a given ID as packed, leaving other items and the original array unchanged. Test a missing ID and a list with no items.