0 day streak
javascript / intermediate
Snippet

Non-Destructive List Reordering with Modern Array toSpliced in State

React requires state updates to be immutable. Modern ECMAScript introduces Array.prototype.toSpliced(), which returns a new shallow copy of an array with elements added or removed rather than mutating the original array in place like Array.prototype.splice().

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
import { useState } from 'react';
export function PriorityTaskList() {
const [tasks, setTasks] = useState(['Review PR', 'Fix CI', 'Write Tests', 'Deploy']);
const moveTask = (fromIndex, toIndex) => {
if (toIndex < 0 || toIndex >= tasks.length) return;
const targetItem = tasks[fromIndex];
const listWithoutItem = tasks.toSpliced(fromIndex, 1);
const reorderedList = listWithoutItem.toSpliced(toIndex, 0, targetItem);
setTasks(reorderedList);
};
return (
<ul>
{tasks.map((task, idx) => (
<li key={task}>
{task}
<button onClick={() => moveTask(idx, idx - 1)}>Up</button>
<button onClick={() => moveTask(idx, idx + 1)}>Down</button>
</li>
))}
</ul>
);
}
react
Breakdown
1
const listWithoutItem = tasks.toSpliced(fromIndex, 1);
Creates a new array copy excluding the item at the initial index without mutating tasks.
2
const reorderedList = listWithoutItem.toSpliced(toIndex, 0, targetItem);
Creates another new array with the target item inserted at the destination index.
3
setTasks(reorderedList);
Updates React state with the newly created immutable array reference.