Sub topic 7
Passing Reactive Values as Arguments
This chapter assumes you know how to declare an Effect Event with useEffectEvent and call it from an Effect. It also assumes you know that an Effect Event always reads the latest props and state. Earlier chapters covered both. Here we look at a design choice that comes up as soon as an Effect Event needs a value the Effect also cares about: should the Effect Event read that value itself, or should the Effect pass it in as an argument?
The short answer: pass the values that define which event happened, and let the Effect Event read the values that only describe the surroundings when it happened.
The Page Visit Example
Suppose you want to log an analytics entry each time a user visits a page. Each log entry should record the URL and the number of items in the shopping cart.
Two values matter here, and they play different roles:
| Value | Should a change trigger a new log entry? | Role |
|---|---|---|
| `url` | Yes. A new URL is a new visit. | Reactive: the Effect depends on it |
| `shoppingCart` | No. Adding an item is not a new visit. | Non-reactive: read only when logging |
Here is a minimal analytics.js so the example runs:
// analytics.js
export function logVisit(url, cartSize) {
console.log(`Visit: ${url} (cart items: ${cartSize})`);
}And here is the component:
import { useEffect, useEffectEvent } from 'react';
import { logVisit } from './analytics.js';
function Page({ url, shoppingCart }) {
const onVisit = useEffectEvent((visitedUrl) => {
logVisit(visitedUrl, shoppingCart.length);
});
useEffect(() => {
onVisit(url);
}, [url]);
}The Effect reads url and passes it to onVisit. Because the Effect reads url, url is a dependency, and the Effect re-runs whenever it changes. The Effect never reads shoppingCart. Only the Effect Event reads it, so changing the cart does not re-run the Effect. When the Effect does run, onVisit still sees the latest cart.
Why Not Just Read `url` Inside the Effect Event?
An Effect Event can read any prop, so this version also works:
import { useEffect, useEffectEvent } from 'react';
import { logVisit } from './analytics.js';
function Page({ url, shoppingCart }) {
const onVisit = useEffectEvent(() => {
logVisit(url, shoppingCart.length);
});
useEffect(() => {
onVisit();
}, [url]); // url is listed, but nothing in the Effect uses it
}It behaves the same in this simple case, but it has two weaknesses.
The dependency looks unused
In this version, the Effect body never mentions url. The [url] array is the only sign that a URL change should produce a new log entry. A teammate who sees a dependency that the body doesn't use may delete it as clutter. After that, the Effect runs once on mount and never again, so navigation stops being logged. Nothing errors, and the bug only shows up in your analytics.
When the Effect reads url and passes it on, the dependency comes from the code. The linter requires it, and deleting it produces a warning.
The argument states your intent
Writing onVisit(url) tells the reader that a visit to a different URL is a separate event. The function signature (visitedUrl) => ... records which input identifies the event. Values read from the closure, such as shoppingCart, are context that gets sampled at that moment.
The Asynchronous Case: Arguments Capture, Closures Read Latest
The difference becomes real once the Effect Event is called later rather than immediately. Suppose you delay logging so a visit counts only after five seconds:
import { useEffect, useEffectEvent } from 'react';
import { logVisit } from './analytics.js';
function Page({ url, shoppingCart }) {
const onVisit = useEffectEvent((visitedUrl) => {
logVisit(visitedUrl, shoppingCart.length);
});
useEffect(() => {
// No cleanup on purpose: every navigation is logged, even quick ones.
setTimeout(() => {
onVisit(url);
}, 5000);
}, [url]);
}Walk through a fast navigation:
- The user lands on
/home. The Effect schedules a timer whose callback capturedurl = "/home". - Two seconds later the user goes to
/products. The Effect runs again and schedules a second timer withurl = "/products". - At five seconds the first timer fires and calls
onVisit("/home"). - At seven seconds the second timer fires and calls
onVisit("/products").
Each log entry gets the URL that started its timer, because the argument was captured when the Effect ran. shoppingCart.length, in contrast, is read when the Effect Event runs, so both entries show the cart as it is at that moment.
Now consider the version that reads url inside the Effect Event. At step 3, the Effect Event reads the latest props, which say url = "/products". Both entries would record /products, and the /home visit would be lost from your data.
| Where `url` comes from | Value seen by the timer callback | Result for a fast navigation |
|---|---|---|
| Argument `onVisit(url)` | URL at the time the Effect ran | `/home`, then `/products` (correct) |
| Read inside the Effect Event | URL at the time the callback runs | `/products`, then `/products` (wrong) |
The same applies to subscriptions, promise callbacks, and any other code that calls the Effect Event after the Effect body has finished.
Common Mistakes
Passing too much
Arguments are not free. Whatever the Effect passes in, it has to read, and whatever it reads becomes a dependency:
useEffect(() => {
onVisit(url, shoppingCart); // Effect now reads shoppingCart
}, [url, shoppingCart]); // so cart changes log a new visit againThis brings back the extra re-runs that Effect Events exist to prevent. Pass only the values that define the event.
Passing a value the Effect doesn't depend on
Sometimes developers pass a value as an argument and then leave it out of the dependency array to avoid re-runs. The linter flags this. If you silence the warning, you get the stale-value bugs described in the next chapter. If you don't want a value to trigger re-runs, don't pass it. Let the Effect Event read it.
Passing objects when a primitive identifies the event
Passing an object such as options makes it a dependency. If the parent creates that object anew on every render, the Effect re-runs on every render. Pass the specific primitive that identifies the event, such as roomId or options.serverUrl, and keep the Effect's dependencies stable.
Arguments with several identifying values
An event can be identified by more than one value. A chat log entry might mean "connected to this room on this server":
import { useEffect, useEffectEvent } from 'react';
function ChatRoom({ roomId, serverUrl, userName }) {
const onConnected = useEffectEvent((room, server) => {
console.log(`${userName} connected to ${room} on ${server}`);
});
useEffect(() => {
const id = setTimeout(() => onConnected(roomId, serverUrl), 100);
return () => clearTimeout(id);
}, [roomId, serverUrl]);
}roomId and serverUrl both identify the connection, so both are passed and both are dependencies. userName is context, so a name change does not log a new connection.
Deciding Where Each Value Goes
For each value an Effect Event uses, ask these questions in order:
- Should a change to this value cause the event to happen again? If yes, the Effect reads it, passes it, and lists it as a dependency.
- Is the Effect Event called after a delay or from a callback, and does it need the value from when the Effect ran? If yes, pass it as an argument, even if you have to think hard about the first question.
- Otherwise, read it inside the Effect Event and leave it out of the dependencies.
Exercise
A component receives productId and currency. Its Effect fetches the product and then calls an Effect Event that logs the product name together with the price formatted in currency. Changing currency should not refetch or log again. Which values should the Effect pass to the Effect Event, and what should the dependency array be?
Show answer
Pass productId (or the fetched product data) as an argument, because it identifies which product was loaded, and use [productId] as the dependency array. Read currency inside the Effect Event so it always uses the latest currency without being a dependency. Passing productId also makes sure a slow response for an earlier product is logged under the correct ID instead of the latest one.
Exercise
In the delayed-logging Page example, a developer changes onVisit(url) to onVisit() and reads url inside the Effect Event, keeping [url] as the dependency array. What changes for a user who navigates from /a to /b within two seconds?
Show answer
Both timers call the Effect Event after the second render, so both read the latest url, which is /b. Two entries are logged for /b and the visit to /a is never recorded. Passing url as an argument captures each URL when its Effect runs, so the entries come out as /a, then /b.