Open this example in the interactive library
Live preview
Source code
// components/ReducerCounter.tsx
import { useReducer } from "react";
export default function ReducerCounter({ initial = 0 }: { initial?: number } = {}) {
const [count, dispatch] = useReducer(
(n: number, a: "add" | "reset") => (a === "reset" ? initial : n + 1),
initial,
);
return (
<div>
<output>{count}</output>
<button onClick={() => dispatch("add")}>Add</button>
<button onClick={() => dispatch("reset")}>Reset</button>
</div>
);
}
