More React answers

by Danny
Published 2 min read

A setInterval inside useEffect keeps reading the first value of state because of a stale closure. Learn why, and fix it with updater functions, dependencies, refs or useEffectEvent.

The short answer

#

The callback you passed to setInterval was created during the first render, so it closed over the state value from that render and keeps reading it forever. If you only need the previous value to calculate the next one, pass an updater function to the setter.


_10
useEffect(() => {
_10
const id = setInterval(() => {
_10
setCount((c) => c + 1); // always uses the latest value
_10
}, 1000);
_10
return () => clearInterval(id);
_10
}, []);

Why it happens

#

Every render of a React component is a fresh function call with its own local variables. When you write const [count, setCount] = useState(0), count is a plain constant for that render. A later render gets a new count constant with the new value, but it does not change the old one.

A function created during a render can see the variables of that render. This is a closure. An effect with an empty dependency array runs only after the first render, so the interval callback it creates sees count as 0 for its whole life.


_10
useEffect(() => {
_10
const id = setInterval(() => {
_10
setCount(count + 1); // count is always 0 here
_10
console.log(count); // logs 0 every second
_10
}, 1000);
_10
return () => clearInterval(id);
_10
}, []);

The counter goes from 0 to 1 and stops, because every tick sets it to 0 + 1. The same problem affects setTimeout, event listeners added in effects, WebSocket message handlers and any callback stored for later.

How to fix it

#

Use an updater function

When the next state depends only on the previous state, pass a function to the setter, as in the short answer. React calls it with the current value, so the closure never needs to read count. This is the simplest fix and the one to reach for first.

Add the value to the dependencies

If the callback needs to read state for another reason, list it as a dependency. The effect then tears down the old interval and creates a new one whenever the value changes.


_10
useEffect(() => {
_10
const id = setInterval(() => {
_10
if (count >= limit) return;
_10
setCount(count + 1);
_10
}, 1000);
_10
return () => clearInterval(id);
_10
}, [count, limit]);

This is correct, but it restarts the timer on every change, which can make ticks drift.

Read the latest value from useEffectEvent

React 19.2 added useEffectEvent. It creates a function that always sees the latest props and state, and it does not need to go in the dependency array. Use it for logic called from an effect that should not restart the effect.


_16
import { useEffect, useEffectEvent, useState } from 'react';
_16
_16
function Ticker({ limit }: { limit: number }) {
_16
const [count, setCount] = useState(0);
_16
_16
const onTick = useEffectEvent(() => {
_16
if (count < limit) setCount(count + 1);
_16
});
_16
_16
useEffect(() => {
_16
const id = setInterval(() => onTick(), 1000);
_16
return () => clearInterval(id);
_16
}, []);
_16
_16
return <p>{count}</p>;
_16
}

Only call the returned function from inside effects, never during render or from event handlers.

Keep the latest value in a ref

On older React versions, store the value in a ref and update the ref on every render. Refs are mutable boxes, so the interval reads ref.current and gets the current value.


_10
const countRef = useRef(count);
_10
countRef.current = count;
_10
_10
useEffect(() => {
_10
const id = setInterval(() => {
_10
console.log('latest count', countRef.current);
_10
}, 1000);
_10
return () => clearInterval(id);
_10
}, []);

React advises against writing refs during render in general, so prefer useEffectEvent where you can.

Common pitfalls

#
  • Silencing the react-hooks/exhaustive-deps lint rule. The warning is usually pointing straight at the stale value.
  • Forgetting clearInterval in the cleanup. In development, Strict Mode will then leave two intervals running.
  • Using setCount(count + 1) twice in a row and expecting it to add 2. Both calls read the same count; use the updater form instead.
  • Putting a function that changes every render into the dependency array. The interval will restart constantly.
#

Was this resource helpful?