JavaScript Snippet

React useInterval Hook (Dan Abramov pattern)

Difficulty: Medium

Calling setInterval inside useEffect breaks the moment the callback closes over stale state. Dan Abramov's useInterval pattern stores the latest callback in a ref so the timer always fires the freshest version without resetting. This snippet covers the canonical pattern, a pause-aware variant that accepts a null delay, and a useTimeout sibling for one-shot timers.

Code Snippets
/

React useInterval Hook (Dan Abramov pattern)

React useInterval Hook (Dan Abramov pattern)

Calling setInterval inside useEffect breaks the moment the callback closes over stale state. Dan Abramov's useInterval pattern stores the latest callback in a ref so the timer always fires the freshest version without resetting. This snippet covers the canonical pattern, a pause-aware variant that accepts a null delay, and a useTimeout sibling for one-shot timers.

JavaScript
Medium
3 snippets
react
hooks
code-template
performance-optimization

1,167 views

33

The two-effect split is the heart of the pattern. The first effect keeps cbRef.current synced with the latest callback (so closures inside the parent component always see fresh state). The second effect creates the actual setInterval and depends only on delay, so changing the callback does NOT tear down and recreate the timer. Without this split, a counter that increments inside the callback would either hold stale state or restart on every render, both of which are common bugs in hand-rolled useInterval code.