Sub topic 11
Effect Events in Timers, Subscriptions, and Async Code
This chapter assumes you know how to declare an Effect Event with useEffectEvent and that an Effect Event reads the latest props and state, both covered in earlier chapters. It also assumes you are comfortable with setInterval, addEventListener, and async/await inside an Effect, including cleanup functions.
Timers, subscriptions, and async callbacks are where Effect Events matter most. In all three, the Effect sets something up once, and a callback runs later, often many times. The question each time is which values the callback should see: the ones from when it was scheduled, or the ones from right now.
Why Delayed Callbacks Go Stale
A callback created inside an Effect is a closure. A closure keeps the variables from the render in which it was created. If an interval callback reads increment, it reads the increment from that render. Later renders do not change it.
Normally you fix this by adding the value to the dependency array. The Effect then tears down and rebuilds the timer or subscription with a fresh closure. That is correct, but it costs something:
- An interval restarts its countdown, so a tick can be delayed or skipped.
- An event listener is removed and added again on every change.
- An async request may be cancelled and sent again, even though the value that changed had nothing to do with the request.
An Effect Event avoids that cost. The Effect schedules a callback that does nothing except call the Effect Event. When the callback runs, the Effect Event reads the values from the most recent render.
Timers
Here is the timer from the Topic Spine. The interval is created once, and each tick reads the current increment.
import { useState, useEffect, useEffectEvent } from 'react';
export default function Timer() {
const [count, setCount] = useState(0);
const [increment, setIncrement] = useState(1);
const onTick = useEffectEvent(() => {
setCount((c) => c + increment);
});
useEffect(() => {
const id = setInterval(() => {
onTick();
}, 1000);
return () => clearInterval(id);
}, []);
return (
<>
<h1>{count}</h1>
<button onClick={() => setIncrement((i) => i + 1)}>
Increment by {increment}
</button>
</>
);
}The functional updater c => c + increment does not make the Effect Event unnecessary. The updater keeps count from going stale, but increment is still read from the closure. Without the Effect Event, increment would have to be a dependency, and every button click would clear the interval and start a new one. If you clicked quickly, the counter could pause, because each click resets the one-second wait.
If delay were a prop, it would belong in the dependency array. A new delay really does need a new interval. You can only get that by re-synchronizing, so that logic stays reactive.
Subscriptions
Subscriptions follow the same pattern. You subscribe once per value that defines the subscription. Then the handler calls an Effect Event for everything else.
This keyboard shortcut listens on window. The listener only needs to be attached once. What it does depends on the latest selectedId and onDelete.
import { useEffect, useEffectEvent } from 'react';
export function useDeleteShortcut(selectedId, onDelete) {
const onKeyDown = useEffectEvent((e) => {
if (e.key === 'Delete' && selectedId !== null) {
onDelete(selectedId);
}
});
useEffect(() => {
function handleKeyDown(e) {
onKeyDown(e);
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
}import { useState } from 'react';
import { useDeleteShortcut } from './useDeleteShortcut.js';
export default function List() {
const [items, setItems] = useState(['a', 'b', 'c']);
const [selectedId, setSelectedId] = useState(null);
useDeleteShortcut(selectedId, (id) => {
setItems((prev) => prev.filter((item) => item !== id));
setSelectedId(null);
});
return (
<ul>
{items.map((item) => (
<li
key={item}
onClick={() => setSelectedId(item)}
style={{ fontWeight: item === selectedId ? 'bold' : 'normal' }}
>
{item}
</li>
))}
</ul>
);
}The caller passes an inline onDelete, which is a new function on every render. Listing it as a dependency would remove and re-add the listener on every render. Wrapping callbacks like this is covered in more depth in the custom Hooks chapter.
Notice that the handleKeyDown wrapper is a plain function defined inside the Effect, and that the Effect registers the wrapper rather than onKeyDown itself. Keep it that way. Pass the wrapper to addEventListener and removeEventListener. Don't hand the Effect Event to outside code. Its identity is not stable, so you cannot rely on it to match when you remove the listener.
If the subscription target were reactive, for example a target element passed as a prop, target would be a dependency. Switching targets must unsubscribe from the old one and subscribe to the new one.
Async Code
In async code, timing becomes subtle. An Effect Event called after an await reads the values from the latest render at the moment of the call, not from when the Effect started. Sometimes you want that. Sometimes you don't.
import { useState, useEffect, useEffectEvent } from 'react';
import { showToast } from './toast.js';
export default function Profile({ userId, locale }) {
const [profile, setProfile] = useState(null);
const onLoaded = useEffectEvent((loadedUserId, data) => {
// locale: latest value. loadedUserId: the id this request was for.
showToast(`${data.name} (#${loadedUserId})`, locale);
});
useEffect(() => {
let ignore = false;
async function load() {
const res = await fetch(`/api/users/${userId}`);
const data = await res.json();
if (!ignore) {
setProfile(data);
onLoaded(userId, data);
}
}
load();
return () => {
ignore = true;
};
}, [userId]);
return <p>{profile ? profile.name : 'Loading…'}</p>;
}Three choices are at work here:
userIdis a dependency. A new user means a new request, which is the reactive part.localeis read inside the Effect Event. If the locale changes while the request is in flight, the toast uses the new locale, and changing the locale does not refetch the profile.userIdis passed as an argument. Inside the Effect Event,loadedUserIdis the id this request was made for, even if the prop has changed since. Reading theuserIdprop from insideonLoadedwould give the latest id instead, which could label old data with the wrong user.
The ignore flag stays in the Effect. It belongs to one specific run of the Effect, and cleanup sets it. An Effect Event cannot replace it, because the Effect Event has no idea which run called it.
| Value source | What the callback sees | Use it for |
|---|---|---|
| Variable captured in the Effect | Value from the render that ran the Effect | Values that define this run (the request's id, the `ignore` flag) |
| Argument passed to the Effect Event | Whatever the Effect passed at call time | Making "which run is this" explicit |
| Prop or state read inside the Effect Event | Value from the latest render | Settings that should not restart anything (theme, locale, callbacks) |
Edge Cases
Calling from a callback scheduled by an Effect
The rule is "call Effect Events only from inside Effects." A callback that an Effect passes to setInterval, addEventListener, then, or an async function counts as inside the Effect, because the Effect created it. Calling the Effect Event from a JSX onClick handler does not count. Use a regular event handler for clicks.
Debounce and throttle
If you debounce with setTimeout inside an Effect, keep the debounced value, such as a search query, as a dependency and let cleanup clear the pending timeout. Put only the side work in an Effect Event, such as logging with the current filters. If you read the query itself from the Effect Event, typing would no longer restart the timer, and the debounce would stop working.
Values read once at setup
If a value is only needed when the subscription is created, such as an initial option passed to a third-party library, read it in the Effect and list it as a dependency. If changing it should not resubscribe, the library probably offers a setter method. Call that method from a separate Effect that depends on the value.
Exercise
A component polls /api/status every intervalMs milliseconds and calls a onStatus prop with each result. The parent passes an inline arrow function for onStatus. Which values belong in the Effect's dependency array, and which should be read through an Effect Event?
Show answer
intervalMs belongs in the dependency array, because a new interval length requires a new interval. onStatus should be called from an Effect Event, because it is a new function on every render and only needs to be the latest version when a result arrives. The Effect then re-runs only when intervalMs changes.
Exercise
In the Profile example, a developer changes onLoaded to take only data and reads the userId prop directly inside it. The user switches from user 1 to user 2 while user 1's request is still in flight. Assuming the ignore flag were removed, what would the toast show for user 1's data, and why does passing userId as an argument prevent this?
Show answer
The Effect Event reads the latest props, so when user 1's response arrives it would read userId as 2 and show user 1's name labeled "#2". Passing userId from the Effect makes the Effect Event use the id captured by that Effect run, which is 1. In the real component, the ignore flag also blocks the stale result.
Exercise
Why is it wrong to write window.addEventListener('keydown', onKeyDown) with the Effect Event itself, instead of wrapping it in a local function?
Show answer
An Effect Event should not be passed to outside code, and its identity is not guaranteed to stay stable. If the reference passed to removeEventListener differs from the one that was added, the listener is never removed. A local wrapper function defined inside the Effect has a stable identity for that Effect run, so cleanup removes exactly the listener that was added.