Open this example in the interactive library
Live preview
Source code
// components/CountdownTimer.tsx
import { useState, useEffect } from "react";
export default function CountdownTimer({ seconds = 10 }: { seconds?: number } = {}) {
const [left, set] = useState(seconds);
useEffect(() => {
if (left <= 0) return;
const timer = setTimeout(() => set((n) => n - 1), 1000);
return () => clearTimeout(timer);
}, [left]);
return <output>{left > 0 ? left + " seconds" : "Time is up"}</output>;
}
