javascript / intermediate
Snippet
Updating React State Immutably Using ECMAScript 2023 Array Methods
Modern JavaScript introduces non-mutating array methods like `toSpliced()` and `toSorted()`. Unlike `splice()` and `sort()`, these methods return a new copy of the array, preventing accidental state mutation bugs in React without needing manual spread copies.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React, { useState } from 'react';export function TodoListManager({ initialItems }) {const [items, setItems] = useState(initialItems);const removeItemByIndex = (index) => {setItems((prev) => prev.toSpliced(index, 1));};const sortItemsByName = () => {setItems((prev) => prev.toSorted((a, b) => a.text.localeCompare(b.text)));};return (<div><button onClick={sortItemsByName}>Sort Alphabetically</button><ul>{items.map((item, index) => (<li key={item.id}>{item.text}<button onClick={() => removeItemByIndex(index)}>Delete</button></li>))}</ul></div>);}
react
Breakdown
1
setItems((prev) => prev.toSpliced(index, 1));
Creates a new array copy without the element at the specified index without mutating previous state.
2
setItems((prev) => prev.toSorted((a, b) => a.text.localeCompare(b.text)));
Returns a new sorted array instance rather than sorting the existing state array in-place.