Sub topic 11
Effect Events in Timers, Subscriptions, and Async Code
This chapter assumes you know how to declare an Effect Event with useEffectEvent, that it reads the latest props and state, and that you can pass values to it as arguments. Here you apply it to code that runs later: interval ticks, subscription callbacks, and resolved promises.
Why Delayed Callbacks Are the Main Use Case
An Effect sets up a timer, a subscription, or a request. The callback it registers runs some time after the Effect itself. If that callback reads a prop or state value directly, there are two bad options:
- List the value as a dependency. The timer or connection then tears down and restarts every time the value changes.
- Leave it out. The callback then keeps the value from the render that created it, which is a stale closure.
An Effect Event avoids both. The Effect registers a small callback that only calls the Effect Event. The Effect Event reads current values at the moment it runs.
Timers
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 interval starts once. Clicking the button changes increment, and the next tick uses the new value. The one-second rhythm does not reset.
Subscriptions
Subscriptions work the same way. The chat example registers connection.on('connected', () => onConnected()). The connection depends only on roomId. The notification reads the latest theme whenever the event fires. The rule of thumb is that whatever decides what to subscribe to belongs in dependencies. Whatever only shapes what happens when the event arrives can go in an Effect Event.
Async Callbacks
Promises add one more question: should the callback see the value from when the request started, or the value from when it finished?
import { useState, useEffect, useEffectEvent } from 'react';
export default function SearchResults({ query, notifyOnLoad }) {
const [results, setResults] = useState([]);
const onLoaded = useEffectEvent((loadedQuery, items) => {
if (notifyOnLoad) {
console.log(`Loaded ${items.length} results for "${loadedQuery}"`);
}
});
useEffect(() => {
let ignore = false;
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((res) => res.json())
.then((items) => {
if (!ignore) {
setResults(items);
onLoaded(query, items);
}
});
return () => {
ignore = true;
};
}, [query]);
return (
<ul>
{results.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}notifyOnLoad is read when the response arrives, so toggling it mid-request takes effect right away and does not refetch. query is passed as an argument, so the log names the query that was actually fetched. If onLoaded read query itself, it could report a newer query than the one that produced these results.
| Value | How it reaches the callback | Sees |
|---|---|---|
| Captured by the Effect, passed as argument | `onLoaded(query, items)` | Value when the Effect ran |
| Read inside the Effect Event | `notifyOnLoad` | Value when the callback runs |
Common Errors
- Passing
onTickstraight tosetInterval(onTick, 1000). This works at runtime, but wrapping it in an arrow function inside the Effect makes it obvious that it is only called from the Effect, which is the rule the linter checks for. - Adding
onTickto the dependency array. Effect Events are not reactive, so leave them out. - Reading a value inside the Effect Event when you needed the one from the start of the request. Pass that value as an argument instead.
Exercise
A component starts a 3-second setTimeout in an Effect that depends on [url]. When the timer fires, it calls logVisit(url, cart.length). You want the log to show the url that started the timer and the cart size at the moment it fires, and you don't want changes to cart to restart the timer. How do you write it?
Show answer
Declare const onTimeout = useEffectEvent((visitedUrl) => { logVisit(visitedUrl, cart.length); });. In the Effect, call const id = setTimeout(() => { onTimeout(url); }, 3000); and return () => clearTimeout(id). Keep the dependencies as [url]. Passing url as an argument fixes it to the value from when the timer started, and cart is read fresh when the timer fires.