javascript / intermediate
Snippet
Non-Mutating Array State Updates Using toSpliced
Modern JavaScript provides non-mutating array methods like Array.prototype.toSpliced(). Unlike the mutating splice() method, toSpliced() creates and returns a shallow copy with modifications, ensuring React receives a new array reference for reliable state tracking.
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
import React, { useState } from 'react';export function TaskList() {const [tasks, setTasks] = useState(['Plan', 'Code', 'Test']);const removeTaskAtIndex = (targetIndex) => {// toSpliced returns a brand new array without mutating the existing stateconst updatedTasks = tasks.toSpliced(targetIndex, 1);setTasks(updatedTasks);};return (<ul>{tasks.map((task, index) => (<li key={task}>{task}<button onClick={() => removeTaskAtIndex(index)}>Delete</button></li>))}</ul>);}
react
Breakdown
1
const [tasks, setTasks] = useState(['Plan', 'Code', 'Test']);
Initializes component state with an array of strings.
2
const updatedTasks = tasks.toSpliced(targetIndex, 1);
Creates a new array copy with the element at targetIndex removed without mutating the state array.
3
setTasks(updatedTasks);
Dispatches the newly referenced array to trigger a safe component re-render.