Sub topic 12
Wrapping Callbacks in Custom Hooks
This chapter assumes you already know how to declare an Effect Event with useEffectEvent and what its rules are. It also assumes you can write a basic custom Hook, meaning a function whose name starts with use and that calls other Hooks.
Custom Hooks often take a callback from the component that calls them. A timer Hook needs to know what to do on each tick. A subscription Hook needs to know what to do when a message arrives. The callback causes trouble when it ends up in the Effect's dependency array.
The problem: inline callbacks change every render
Here is a first attempt at a useInterval Hook:
import { useEffect } from 'react';
export function useInterval(callback, delay) {
useEffect(() => {
const id = setInterval(() => {
callback();
}, delay);
return () => clearInterval(id);
}, [callback, delay]);
}The linter is satisfied, because callback is a reactive value and it is listed. Now look at a typical caller:
useInterval(() => {
setCount((c) => c + step);
}, 1000);The arrow function is a new object on every render. The callback dependency therefore changes on every render, and React clears and re-creates the interval each time. If the component renders more often than once per second, the interval may never fire at all.
You could ask every caller to wrap the callback in useCallback. That moves the burden to every caller, and it fails again as soon as the callback reads a value that changes, such as step.
The fix: wrap the callback in an Effect Event
The callback is non-reactive logic. The interval should restart when delay changes, but not when the code that runs on each tick changes. Wrap the callback inside the Hook:
import { useEffect, useEffectEvent } from 'react';
export function useInterval(callback, delay) {
const onTick = useEffectEvent(callback);
useEffect(() => {
const id = setInterval(() => {
onTick();
}, delay);
return () => clearInterval(id);
}, [delay]);
}onTick always calls the callback from the latest render, so it sees the current step. The Effect depends only on delay. This follows the rules: the Effect Event is declared and called inside the same Hook, and it is left out of the dependency array.
A full component using it:
import { useState } from 'react';
import { useInterval } from './useInterval.js';
export default function Counter() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
useInterval(() => {
setCount((c) => c + step);
}, 1000);
return (
<>
<h1>{count}</h1>
<button onClick={() => setStep((s) => s + 1)}>
Step: {step}
</button>
</>
);
}Clicking the button changes step. The next tick uses the new step, and the interval keeps running without being reset.
Keep the Effect Event inside the Hook
The Effect Event is a private detail of the Hook. Do not return onTick from useInterval, and do not pass it on to another Hook or component. Callers should keep passing ordinary functions. If a caller needs to react to a value, that value should be a normal Hook parameter in the dependency array, as delay is here.
| Hook parameter | Role | Treatment |
|---|---|---|
| `callback` | What to do when something happens | Wrap in `useEffectEvent` |
| `delay` | How the Effect is set up | Keep in the dependency array |
Exercise
You write useChatMessages(roomId, onMessage), which subscribes to a room and calls onMessage for each incoming message. Which parameter should be wrapped in an Effect Event, and what goes in the dependency array?
Show answer
Wrap onMessage with useEffectEvent and call that Effect Event from inside the subscription handler. The dependency array is [roomId], so the Hook resubscribes only when the room changes. A new inline onMessage on each render does not trigger a resubscribe.
Exercise
Why is asking callers to wrap their callback in useCallback a worse fix than using useEffectEvent inside the Hook?
Show answer
Every caller has to remember to do it. Also, as soon as the callback reads changing state or props, those values must go in the useCallback dependencies, so the callback changes anyway and the Effect still restarts. useEffectEvent inside the Hook fixes this once for every caller and always reads the latest values.