reactjs / reactjs/react.dev

Questionable Comment in the `useEvent` Example

Open
#5,280 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

I found a paragraph from Separating Events from Effects in the beta React Docs, which I couldn't wrap my head around:

In this example, url inside onVisit corresponds to the latest url (which could have already changed), but visitedUrl corresponds to the url that originally caused this Effect (and this onVisit call) to run.

The mentioned example is effectively the one below:

function Page({ url }) {
  const { items } = useContext(ShoppingCartContext);
  const numberOfItems = items.length;

  const onVisit = useEvent(visitedUrl => {
    // `url` captured here is claimed to be the latest, not the original
    // but what about `numberOfItems`?
    logVisit(visitedUrl, numberOfItems);
  });

  // intend to log the `url` that originally caused this Effect, 
  // along with the original `numberOfItems`.
  useEffect(() => {
    setTimeout(() => {
      onVisit(url);
    }, 5000); // Delay logging visits
  }, [url]);

  // ...
}

More essentially, I believe my confusion stems from the claims below:

This solves the problem. Similar to the set functions returned from useState, all Event functions are stable: they never change on a re-render. This is why you can skip them in the dependency list. They are not reactive.

How can Event functions like onVisit are stable, when they need to capture the relevant reactive values like numberOfItems?

Are they stable, but have access to the freshly-constructed anonymous function, which captures the relevant reactive values?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the “Separating Events from Effects” example linked in the issue and compare the claims about useEvent stability with the shown numberOfItems and url values. Done means the documentation clearly resolves which values the delayed callback observes and explains why the event function can be omitted from dependencies.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.