Sub topic 12
Wrapping Callbacks in Custom Hooks
This chapter assumes you already know how to declare an Effect Event with useEffectEvent, that Effect Events read the latest props and state, and the basic rules for calling them. Here we apply those ideas to a common situation: a custom Hook that takes a callback from its caller.
The Problem with Callback Parameters
Custom Hooks often accept functions. A useInterval Hook takes "what to do on each tick." A useChatRoom Hook takes "what to do when a message arrives." Callers usually pass these functions inline:
useInterval(() => {
setCount((c) => c + step);
}, 1000);An inline arrow function is a new function object on every render. If the Hook's Effect lists that callback as a dependency, the Effect tears down and sets up again on every render of the caller. The caller did nothing wrong. They wrote ordinary React code.
The naive version
import { useEffect } from 'react';
export function useInterval(callback, delay) {
useEffect(() => {
const id = setInterval(callback, delay);
return () => clearInterval(id);
}, [callback, delay]);
}This passes the linter, and it looks correct. In practice it fails in two ways:
- Each tick usually updates state, which re-renders the caller, which creates a new
callback, which clears and recreates the interval. The timer restarts on every tick and slowly drifts. - If something else re-renders the caller more often than
delay, the interval never fires. A user typing in a text field on the same component re-renders it on each keystroke. With a 1000 ms delay and someone typing faster than one key per second, the callback never runs.
Callers can work around this with useCallback. That pushes the problem onto every call site, and it only helps when the callback's own dependencies rarely change. If the callback reads step and step changes, useCallback returns a new function and the interval resets anyway.
Wrapping the Callback in an Effect Event
The tick callback does not describe what the Effect synchronizes with. The interval itself depends only on delay. The callback is something the Effect notifies when a tick happens. That makes it non-reactive logic, and non-reactive logic belongs in an Effect Event.
import { useEffect, useEffectEvent } from 'react';
export function useInterval(callback, delay) {
const onTick = useEffectEvent(callback);
useEffect(() => {
if (delay === null) {
return; // a null delay pauses the interval
}
const id = setInterval(() => {
onTick();
}, delay);
return () => clearInterval(id);
}, [delay]);
}Now:
onTickalways calls thecallbackfrom the most recent render, so it sees the caller's latest props and state.- The Effect depends only on
delay. Changing the delay restarts the interval, and passingnullstops it. - Callers can pass inline functions freely, with no
useCallbackneeded.
Here is a complete 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);
const [running, setRunning] = useState(true);
const [note, setNote] = useState('');
useInterval(() => {
setCount((c) => c + step);
}, running ? 1000 : null);
return (
<>
<h1>{count}</h1>
<button onClick={() => setStep((s) => s + 1)}>Step: {step}</button>
<button onClick={() => setRunning((r) => !r)}>
{running ? 'Pause' : 'Resume'}
</button>
<input
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder="Type here; the timer keeps ticking"
/>
</>
);
}Typing in the input re-renders Counter on every keystroke, and the interval still fires on schedule. Clicking "Step" changes what each tick adds without resetting the timer. Clicking "Pause" changes delay to null, and that is the only change that re-synchronizes the Effect.
Sorting Hook Parameters: Reactive or Not
When you design a Hook, go through each parameter and decide which role it plays.
| Parameter kind | Example | Role | Where it goes |
|---|---|---|---|
| Configuration of the external system | `roomId`, `serverUrl`, `delay` | Defines what to synchronize with | Effect dependency array |
| Notification callback | `onMessage`, `onTick`, `onError` | Runs when something happens | Wrap in `useEffectEvent` |
| Data read only inside a notification | `theme` used inside `onMessage` | Read at the moment of the event | Captured by the callback, not a dependency |
| Factory that builds the connection | `createSocket` | Defines what to synchronize with | Usually a dependency; ask callers to keep it stable |
A useful test is to ask: "If this value changes, should the subscription be thrown away and rebuilt?" If yes, it's a dependency. If the answer is "no, just use the new value next time something happens," wrap it in an Effect Event.
A Subscription Hook
The same pattern works for subscriptions. Here is a small fake chat module so the example runs on its own:
// chat.js
export function createConnection({ serverUrl, roomId }) {
let intervalId = null;
let messageHandler = null;
return {
connect() {
console.log(`Connecting to "${roomId}" at ${serverUrl}`);
intervalId = setInterval(() => {
if (messageHandler) {
messageHandler(`Hello from ${roomId} at ${new Date().toLocaleTimeString()}`);
}
}, 3000);
},
on(event, handler) {
if (event === 'message') {
messageHandler = handler;
}
},
disconnect() {
console.log(`Disconnected from "${roomId}"`);
clearInterval(intervalId);
messageHandler = null;
},
};
}// useChatRoom.js
import { useEffect, useEffectEvent } from 'react';
import { createConnection } from './chat.js';
export function useChatRoom({ serverUrl, roomId, onReceiveMessage }) {
const onMessage = useEffectEvent((msg) => {
onReceiveMessage(msg);
});
useEffect(() => {
const connection = createConnection({ serverUrl, roomId });
connection.on('message', (msg) => {
onMessage(msg);
});
connection.connect();
return () => connection.disconnect();
}, [serverUrl, roomId]);
}// ChatRoom.js
import { useState } from 'react';
import { useChatRoom } from './useChatRoom.js';
export default function ChatRoom({ roomId }) {
const [muted, setMuted] = useState(false);
const [messages, setMessages] = useState([]);
useChatRoom({
serverUrl: 'https://localhost:1234',
roomId,
onReceiveMessage(msg) {
if (!muted) {
setMessages((list) => [...list, msg]);
}
},
});
return (
<>
<label>
<input
type="checkbox"
checked={muted}
onChange={(e) => setMuted(e.target.checked)}
/>
Mute
</label>
<ul>
{messages.map((m, i) => (
<li key={i}>{m}</li>
))}
</ul>
</>
);
}Toggling "Mute" changes what the handler does with the next message, and the console shows no reconnect. Changing roomId reconnects, which is what you want.
Gotchas Specific to Hooks
Don't return the Effect Event from the Hook
An Effect Event may only be called from Effects in the component (or Hook) that declared it. Returning it lets the caller invoke it from a click handler or during render, and both break the rule.
// Wrong: leaks the Effect Event to the caller
export function useTicker(callback) {
const onTick = useEffectEvent(callback);
// ...
return onTick;
}If callers need an imperative function, return a normal function, and if it must be stable, build it with useCallback.
Don't pass an Effect Event into another Hook
Composing Hooks is normal, but pass the plain callback down and let the inner Hook do its own wrapping:
import { useState } from 'react';
import { useInterval } from './useInterval.js';
export function useCountdown(seconds, onFinish) {
const [left, setLeft] = useState(seconds);
// Right: pass an ordinary function; useInterval wraps it itself
useInterval(() => {
if (left <= 1) {
setLeft(0);
onFinish();
} else {
setLeft(left - 1);
}
}, left > 0 ? 1000 : null);
return left;
}Writing const onDone = useEffectEvent(onFinish); useInterval(onDone, 1000); breaks the rule against handing Effect Events to other Hooks. The linter reports it. It's also unnecessary, because useInterval already guarantees the latest callback runs.
Don't wrap a callback whose change should re-synchronize
Some function parameters really are configuration. If a Hook takes getUrl and calls it once during setup to decide where to connect, wrapping it in an Effect Event means a new getUrl will never cause a reconnect. That's a silent bug. Either accept the resulting value (url) as a dependency instead, or keep the function in the dependency array and document that callers should memoize it. Accepting the value is usually the cleaner API.
Forward arguments explicitly
useEffectEvent(callback) passes arguments through and returns the callback's return value. Writing a small wrapper, as useChatRoom does with (msg) => onReceiveMessage(msg), makes the Hook's contract with the callback obvious to readers, and it lets you adapt arguments before passing them on.
Exercises
Exercise
A teammate writes useWindowListener(eventName, handler) with useEffect(() => { window.addEventListener(eventName, handler); return () => window.removeEventListener(eventName, handler); }, [eventName, handler]). Callers pass inline handlers. What goes wrong, and how do you fix it?
Show answer
Every render of the caller creates a new handler, so the listener is removed and re-added on every render. Wrap the handler: const onEvent = useEffectEvent(handler); then inside the Effect register a listener function, const listener = (e) => onEvent(e);, add and remove that same listener, and depend only on [eventName]. The listener is rebuilt only when the event name changes, and it always runs the latest handler.
Exercise
A Hook useFetchJson(buildUrl, onData) calls buildUrl() once inside its Effect to get the request URL, then calls onData(json) when the response arrives. Which parameter should be wrapped in an Effect Event, and which should not?
Show answer
Wrap onData, because it is a notification run when data arrives and its changes shouldn't trigger a new request. Don't wrap buildUrl, because it decides what to fetch. Wrapping it would mean a changed URL never refetches. A better API accepts url as a string and lists it as a dependency.
Exercise
Why is it a mistake for useInterval to return its onTick Effect Event so a caller can trigger a tick from a button?
Show answer
Effect Events may only be called from Effects in the component or Hook that declares them. Calling one from the caller's click handler breaks that rule, and the lint rule flags it. If the caller wants to trigger the action manually, it should call its own callback directly from the event handler.