0 day streak
javascript / expert
Snippet

Reactive State History via Snapshots

To implement undo/redo logic in Svelte 5, you must capture the current value of a proxy-based $state. The $state.snapshot utility converts a reactive proxy back into a plain JavaScript object, allowing it to be safely stored in an array without remaining linked to future mutations.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
let data = $state({ x: 0, y: 0 });
let history = $state([]);
function saveStep() {
const snapshot = $state.snapshot(data);
history.push(structuredClone(snapshot));
}
function undo() {
if (history.length > 0) data = history.pop();
}
svelte
Breakdown
1
$state.snapshot(data)
Removes the reactive proxy wrapper to get a static version of the data.
2
data = history.pop()
Reassigning the state variable triggers a UI update with the previous snapshot.