Sub topic 10
Reading the latest callback through a ref
This chapter assumes you know useState, useEffect, closures, and the dependency array. You should also know why a hook's effect re-runs when a dependency changes. It covers one pattern: storing the newest callback in a ref so an effect can call it without depending on it.
The problem: callbacks in dependency arrays
A hook that accepts a callback has a design problem. The effect needs to call the callback. The callback is usually an inline arrow function, which is a new object on every render. If you list it as a dependency, the effect tears down and re-runs on every render.
Here is a naive event listener hook.
import { useEffect } from 'react';
export function useEventListenerNaive(type, handler, target = window) {
useEffect(() => {
target.addEventListener(type, handler);
return () => target.removeEventListener(type, handler);
}, [type, handler, target]);
}This hook is correct, because handler is listed. It is also wasteful when the caller passes (e) => setX(e.clientX). The listener is removed and added again after each render. For a listener, that is only churn. For an effect that opens a socket or starts an interval, re-running can break behavior.
You have three options:
- Leave
handlerout of the array. The effect then calls a stale closure, and the linter warns you. - Make every caller wrap the handler in
useCallback. This pushes work onto callers and is easy to forget. - Keep the latest handler in a ref and read it when the event fires.
The third option is the subject of this chapter.
Why a ref works
A ref created with useRef is a plain object, { current: value }. React returns the same object on every render. Changing current does not trigger a re-render. Effects can read it at any time.
Two properties make it useful here:
- The ref object has a stable identity, so the effect does not need it as a dependency to stay correct.
ref.currentcan be updated each render, so it always points at the handler from the most recent render.
The effect installs a small wrapper function once. When the event fires, the wrapper reads handlerRef.current and calls whatever is there at that moment.
The pattern
import { useEffect, useRef } from 'react';
export function useEventListener(type, handler, target = window) {
const handlerRef = useRef(handler);
useEffect(() => {
handlerRef.current = handler;
});
useEffect(() => {
const listener = (event) => handlerRef.current(event);
target.addEventListener(type, listener);
return () => target.removeEventListener(type, listener);
}, [type, target]);
}There are two effects with different jobs.
- The first has no dependency array, so it runs after every render. It copies the newest
handlerinto the ref. - The second has
[type, target]. It attaches the listener only when the event type or the target changes.
The listener wrapper never changes. It delegates to the ref, so the caller's newest function runs.
The order matters. Effects run in the order they are declared, so the ref is updated before the listener could fire from a later event.
Using it
import { useState } from 'react';
import { useEventListener } from './useEventListener';
function PointerReadout() {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [paused, setPaused] = useState(false);
useEventListener('pointermove', (event) => {
if (!paused) setPosition({ x: event.clientX, y: event.clientY });
});
return (
<div>
<p>{position.x}, {position.y}</p>
<button onClick={() => setPaused((p) => !p)}>
{paused ? 'Resume' : 'Pause'}
</button>
</div>
);
}The handler is a new function each render and reads paused. The listener is attached once for 'pointermove' on window. Because the ref always holds the latest handler, paused is never stale.
Seeing the stale closure it prevents
Suppose you skip the ref and omit handler from the dependencies to avoid re-attaching.
import { useEffect } from 'react';
export function useEventListenerStale(type, handler, target = window) {
useEffect(() => {
target.addEventListener(type, handler);
return () => target.removeEventListener(type, handler);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [type, target]);
}The effect captured the handler from the first render. In the example above, paused would stay false forever inside that handler, even after you press the button. The ref pattern fixes this without re-attaching.
Where else the pattern applies
The same shape works whenever an effect should be driven by some inputs but should call other inputs "whenever it happens to fire".
Intervals with a changing callback
import { useEffect, useRef } from 'react';
export function useInterval(callback, delay) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
});
useEffect(() => {
if (delay === null) return undefined;
const id = setInterval(() => callbackRef.current(), delay);
return () => clearInterval(id);
}, [delay]);
}The interval restarts only when delay changes. Passing null pauses it. Without the ref, a callback that reads state would either restart the timer every render or read old state.
Callbacks fired from async code
A data hook might accept onSuccess. Calling onSuccessRef.current(data) inside the .then lets the caller pass an inline function. The fetch does not restart when that function changes.
Updating the ref: effect or render?
You may see code that assigns during render:
import { useRef } from 'react';
function useLatestRender(value) {
const ref = useRef(value);
ref.current = value; // written during render
return ref;
}This looks simpler, but writing to a ref during render is a side effect in the render phase. React may render a component and then discard the result, as happens with concurrent rendering. Then ref.current could hold a value from a render that never committed. React's documentation recommends writing refs in effects or event handlers, except for lazy initialization. The two-effect version above follows that advice.
If your handler must run in a layout-sensitive moment, you can use useLayoutEffect for the assignment. It runs before the browser paints and before other effects. For most listeners, useEffect is enough.
Extracting the pattern
If you use it in several hooks, put it in its own hook.
import { useEffect, useRef } from 'react';
export function useLatest(value) {
const ref = useRef(value);
useEffect(() => {
ref.current = value;
});
return ref;
}useEventListener then becomes shorter.
import { useEffect } from 'react';
import { useLatest } from './useLatest';
export function useEventListener(type, handler, target = window) {
const handlerRef = useLatest(handler);
useEffect(() => {
const listener = (event) => handlerRef.current(event);
target.addEventListener(type, listener);
return () => target.removeEventListener(type, listener);
}, [type, target, handlerRef]);
}The linter does not know that the object returned by a custom hook is stable, so handlerRef is listed. It never changes, so listing it costs nothing.
Edge cases and limits
- The ref is not reactive. Changing
ref.currentdoes not re-render. Use the pattern only for values the effect reads at call time, not values the UI displays. - Do not hide real dependencies. If the effect should restart when a value changes, such as a URL or a room ID, keep that value in the dependency array. Put only the "what to do when something happens" callbacks in the ref.
- Reading during render. Do not read
ref.currentwhile rendering to produce output. It may be one render behind. - Timing gap. Between a render and its effects running, the ref still holds the previous handler. An event in that small window calls the older function. This is rarely a problem, and it is the reason to prefer
useLayoutEffectfor the assignment if it matters. - The
targetargument. Passingwindowas a default is fine, because it is a stable object. Passing a new object or a ref'scurrenteach render needs care, since changes totargetre-attach the listener. - Server rendering. The default
target = windowis evaluated when the hook runs. That throws on a server wherewindowis undefined. Effects do not run on the server, but a default parameter is evaluated during render. Guard it if you render on the server.
Newer alternative: `useEffectEvent`
React has an useEffectEvent API for the same need. It declares a function that always sees the latest props and state but is not a reactive dependency. Check your React version and its documentation before using it, since it was introduced as experimental and is available in newer releases. The ref pattern works in every version that has hooks, and explains what such an API does internally.
Choosing between the options
| Situation | Approach |
|---|---|
| Callback is stable, such as one from `useCallback` | List it as a dependency |
| Caller passes inline functions, and re-running the effect is harmful or wasteful | Latest-value ref |
| The value should restart the effect when it changes | Keep it in the dependency array |
| You need the value to appear in the UI | State, not a ref |
Summary of the working model
- Render produces a new callback each time.
- A no-dependency effect stores it in a ref after each commit.
- A second effect, keyed on the real inputs, installs a wrapper once.
- The wrapper reads the ref when the event happens.
Exercise
A hook useInterval(callback, delay) is written as useEffect(() => { const id = setInterval(callback, delay); return () => clearInterval(id); }, [callback, delay]);. A component passes () => setCount(count + 1) inline. What goes wrong, and how do you fix it with a ref?
Show answer
The inline callback is a new function every render, so the effect cleans up and starts a new interval after every render. If the component re-renders more often than the delay, the interval may never fire. Fix it by storing the callback in a ref updated in an effect without a dependency array, then calling callbackRef.current() from a wrapper inside setInterval, with [delay] as the only dependency.
Exercise
In useEventListener, why must type and target stay in the dependency array while handler does not?
Show answer
type and target define what the listener is attached to, so a change in either means the old listener must be removed and a new one attached. handler only defines what happens when an event fires, and the ref lets the stable wrapper read the newest one at that time.