Skip to content

Conversation

@djk01281
Copy link

@djk01281 djk01281 commented Feb 3, 2026

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 calls unobserve() which removes the callback from the array using splice(). This modifies the array during forEach iteration, causing subsequent callbacks to be skipped.

Solution

Copy the callbacks array before iterating using the spread operator:

[...elements.get(entry.target) ?? []].forEach((callback) => {
  callback(inView, entry);
});

This prevents the iteration from being affected by array modifications.

Changes

  • src/observe.ts: Use spread operator to copy callbacks array before iteration
  • src/tests/useInView.test.tsx: Add test case to verify all callbacks are triggered with triggerOnce and merged refs

Testing

Added a new test that reproduces the bug:

  • Creates 3 useInView hooks with triggerOnce: true
  • Merges all refs onto a single element
  • Verifies all 3 hooks receive inView: true
image

Before fix: Test fails - only hooks 1 and 3 trigger, hook 2 remains false


image

After fix: Test passes - all 3 hooks trigger correctly : )

@bolt-new-by-stackblitz
Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@vercel
Copy link

vercel bot commented Feb 3, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
react-intersection-observer Ready Ready Preview, Comment Feb 3, 2026 1:36pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug: Callbacks skipped when using triggerOnce with merged refs

1 participant