Skip to content

[@mantine/hooks] use-intersection: Use the last entry from a batched observer callback#9019

Open
greymoth-jp wants to merge 1 commit into
mantinedev:masterfrom
greymoth-jp:use-intersection-last-batched-entry
Open

[@mantine/hooks] use-intersection: Use the last entry from a batched observer callback#9019
greymoth-jp wants to merge 1 commit into
mantinedev:masterfrom
greymoth-jp:use-intersection-last-batched-entry

Conversation

@greymoth-jp

Copy link
Copy Markdown

Follow-up to #8509, which fixed the same issue in use-in-viewport.

useIntersection reads only the first entry from the observer callback:

new IntersectionObserver(([_entry]) => {
  setEntry(_entry);
}, options);

When the callback is delayed across frames (busy main thread, fast scrolling), the browser can queue more than one IntersectionObserverEntry for the observed element and deliver them in a single call. The first entry then holds an older state and the last one holds the current state, so the hook can report a stale entry. This is the same situation #8509 describes for use-in-viewport.

The fix mirrors #8509: read the last entry.

new IntersectionObserver((entries) => {
  setEntry(entries[entries.length - 1]);
}, options);

I left use-resize-observer as it is even though it also reads entries[0]: a ResizeObserver reports the current size of each target once per delivery instead of accumulating one entry per frame, so its first entry is already the latest.

Added a regression test that feeds a mock observer a two-entry batch and checks the hook keeps the last entry. Without the change the test fails because the hook returns the stale first entry.

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.

1 participant