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

Files touched

--- 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>;
+}

Review this PR

React practice