Open this example in the interactive library
Live preview
Source code
// components/UndoCounter.tsx
import { useState } from "react";
export default function UndoCounter({ initial = 0 }: { initial?: number } = {}) {
const [history, set] = useState([initial]);
return (
<div>
<output>{history.at(-1)}</output>
<button onClick={() => set((h) => [...h, h[h.length - 1] + 1])}>Increment</button>
<button disabled={history.length < 2} onClick={() => set((h) => h.slice(0, -1))}>
Undo
</button>
</div>
);
}
