prevent callback skipping with triggerOnce and merged refs - #747
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
965a07c to
9b4e330Compare9b4e330 to
50f709dComparecommit: |
thebuilder
commented
Feb 6, 2026
Looks good, thanks for fixing it. On vacation, but will release it in a couple of weeks. |
There was a problem hiding this comment.
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.
Uh oh!
There was an error while loading. Please reload this page.
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 : )