Update state on an interval with cleanup.
Section: UI Recipes
Build an interval counter
tsx
tsx
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds(s => s + 1), 1000);
return () => clearInterval(id);
}, []);Explanation
Uses the updater form to avoid stale state issues.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing UI Recipes
Mirror a prop into state only when necessary
Initialize from props, then manage locally.
Focus an input on mount
Use a ref and an effect to focus an input after mount.
Optimistic UI with transition
Apply urgent optimistic state and schedule reconciliation.