-
Notifications
You must be signed in to change notification settings - Fork 190
prevent callback skipping with triggerOnce and merged refs #747
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
965a07c to
9b4e330
Compare
9b4e330 to
50f709d
Compare
commit: |
|
Looks good, thanks for fixing it. On vacation, but will release it in a couple of weeks. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
Fixes a regression/edge-case in the IntersectionObserver callback dispatch where multiple useInView({ triggerOnce: true }) listeners attached to the same element (via merged refs) could be skipped due to in-loop mutation of the callbacks array.
Changes:
- Prevent callback skipping by iterating over a copied callbacks array in the observer entry handler.
- Add a regression test covering multiple
triggerOncehooks merged onto a single element.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
src/observe.ts |
Iterates over a snapshot of the callbacks list to avoid splice() mutation during iteration. |
src/__tests__/useInView.test.tsx |
Adds a test reproducing and validating the fix for merged refs + triggerOnce. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Hello! 👋🏻 I ran into this bug while using multiple
useInViewhooks with merged refs, so I opened an issue and put together this fix.Let me know if anything needs to be changed!
Loving the library by the way : )
Description
Fixes #746
This PR fixes a bug where callbacks are skipped when multiple
useInView({ triggerOnce: true })hooks are merged on the same element.Problem
When a callback executes with
triggerOnce: true, it callsunobserve()which removes the callback from the array usingsplice(). This modifies the array duringforEachiteration, causing subsequent callbacks to be skipped.Solution
Copy the callbacks array before iterating using the spread operator:
This prevents the iteration from being affected by array modifications.
Changes
triggerOnceand merged refsTesting
Added a new test that reproduces the bug:
useInViewhooks withtriggerOnce: trueinView: trueBefore fix: Test fails - only hooks 1 and 3 trigger, hook 2 remains
falseAfter fix: Test passes - all 3 hooks trigger correctly : )