ARTICLE AD BOX
I'm building a simple timer component in React using setInterval to increment a counter every second. However, the state variable seconds never updates inside the interval callback – it always logs 0, and the displayed value stays 0.
Here's my minimal example:
javascript
import React, { useState, useEffect } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { console.log(seconds); // always logs 0 setSeconds(seconds + 1); // tries to update }, 1000); return () => clearInterval(interval); }, []); // empty dependency array return <div>{seconds}</div>; }What I expected:
seconds would increase by 1 every second, so the log would show 0, 1, 2, ... and the <div> would update accordingly.
What actually happens:
The log stays at 0, and the <div> never changes from 0.
What I tried:
Using the functional update pattern: setSeconds(prev => prev + 1) – still the same problem (log still shows 0, but the display remains 0 as well).
Adding seconds to the dependency array [seconds] – then the interval is re-created every second, which defeats the purpose and also behaves incorrectly.
Using useRef to keep the latest value – that works, but I want to understand why the normal state approach fails.
Question:
Why does seconds stay stale inside setInterval even when I use a functional update? How can I correctly update state at a fixed interval without restarting the timer every time?
