Auto-incrementing seconds counter
React · React · intermediate · greenfield
Adds a seconds counter driven by a single setInterval started on mount and cleared on unmount. The empty dependency array makes sure the interval is created only once. Counts up as expected.
A small 'time on page' widget mounted on the article view.
Requirements
- Show a counter that starts at 0 and increases by 1 every second.
- Use a single interval started once when the component mounts.
- Clear the interval when the component unmounts.
Files touched
- src/components/SecondsCounter.jsx
--- src/components/SecondsCounter.jsx
+import { useEffect, useState } from 'react';
+
+export function SecondsCounter() {
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ const id = setInterval(() => {
+ setCount(count + 1);
+ }, 1000);
+ return () => clearInterval(id);
+ }, []);
+
+ return <p>{count}s</p>;
+}