Questionable Comment in the `useEvent` Example
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,
urlinsideonVisitcorresponds to the latesturl(which could have already changed), butvisitedUrlcorresponds to theurlthat originally caused this Effect (and thisonVisitcall) 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
setfunctions returned fromuseState, 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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