Sub topic 10
Reading the latest callback through a ref
This chapter assumes you know useState, useEffect with cleanup, useCallback, closures, and how dependency arrays decide when an effect re-runs. Earlier chapters covered these.
The problem: a handler that changes every render
Suppose a hook attaches a browser event listener and accepts a handler from the caller. Callers usually pass an inline arrow function, which is a new function on every render.
You have two options for the effect, and both are flawed:
- List
handlerin the dependency array. The effect re-runs on every render. The hook removes and re-adds the listener each time, which is wasteful and can miss events fired between the removal and the re-add. - Leave
handlerout. The listener keeps the first closure forever. It reads stale props and state.
You could ask callers to wrap their handler in useCallback. That works, but it pushes work onto every caller and breaks silently when one forgets. A ref lets the hook handle it.
The pattern: store the handler in a ref
A ref created by useRef is a mutable box that survives re-renders. Changing ref.current does not cause a re-render, and the effect does not depend on it. The hook stores the newest handler in the box. The listener reads from the box when an event fires.
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]);
}The hook has two effects:
- The first has no dependency array, so it runs after every render and copies the latest
handlerinto the ref. - The second subscribes once per
typeandtarget. Itslisteneris a stable wrapper that looks uphandlerRef.currentat call time, so it always runs the newest handler.
Using it
The component below passes an inline handler that reads count. The listener is attached once, and each key press still sees the current count.
import { useState } from 'react';
import { useEventListener } from './useEventListener';
function KeyCounter() {
const [count, setCount] = useState(0);
useEventListener('keydown', (event) => {
if (event.key === ' ') setCount(count + 1);
});
return <p>Space pressed {count} times</p>;
}Gotchas
- Update the ref in an effect, not during render. Writing
handlerRef.current = handlerin the hook body is a side effect in render. React may render without committing, so the ref could hold a handler from a render that never appeared on screen. - Keep the ref-updating effect first. Effects run in declaration order, so the ref is current before any later effect uses it.
- Do not hide values that should trigger re-subscription.
typeandtargetstay in the dependency array because changing them must move the listener. Only the callback goes through the ref. - Refs do not re-render. Use this pattern for values read inside callbacks. Do not use it for values the component displays.
- The
windowdefault fails during server rendering. Code that runs on the server has nowindow. Pass a target explicitly there, or guard the default.
Exercise
A hook useInterval(callback, delay) calls setInterval in an effect that lists [callback, delay] as dependencies. The interval keeps restarting because callers pass inline functions. How would you fix it using a ref, and which value stays in the dependency array?
Show answer
Store callback in a ref and update ref.current in an effect that runs after every render. Create the interval in a second effect that calls ref.current() inside the tick function. Keep only delay in that effect's dependency array, because changing the delay must restart the timer, but changing the callback must not.