Skip to content
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

WhenVisible useEffect function is not recreated when params change. #2152 #2153

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

Loeffeldude
Copy link

Closes #2152. Adds the needed dependencies to the useEffect and adds a few refs to keep the same fetching behavior as before.

Copy link

@PedroAugustoRamalhoDuarte PedroAugustoRamalhoDuarte left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR @Loeffeldude !!

packages/react/src/WhenVisible.ts Outdated Show resolved Hide resolved
@joetannenbaum
Copy link
Contributor

joetannenbaum commented Jan 8, 2025

Thanks for the PR @Loeffeldude. I'm a little confused as to why the fetching flag was split into two separate flags and converted to refs. If I revert it back to a simple useState it seems to work as expected, want to make sure I'm not missing something.

@Loeffeldude
Copy link
Author

We split into two refs (fetchedOnceRef and fetchingRef) because we're handling two distinct problems:

Has this content ever been fetched? (for the always prop logic)
Is there currently a fetch in progress? (to prevent concurrent fetches)

Using a single useState for fetching would create problems because:

State updates are asynchronous and will trigger rerenders
The IntersectionObserver callback can fire multiple times while a fetch is in progress
When props like buffer change, the effect recreates the observer callback, which could capture stale state values

Using refs:

  • Avoids unnecessary rerenders
  • Provides synchronous access in the observer callback
  • Prevents race conditions
  • Correctly handles the always prop logic
  • Maintains correct behavior when the effect needs to recreate the observer

The ref-based approach is more robust for handling edge cases and async behavior.

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.

WhenVisible useEffect function is not recreated when params change.
3 participants