Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/light-jobs-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'react-simplikit': patch
---

`useIntersectionObserver` no longer recreates the underlying `IntersectionObserver` on every render when an inline `options` object is passed. It now recreates it only when `root`, `rootMargin`, or `threshold` actually change.
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,49 @@ describe('useIntersectionObserver', () => {

expect(mockObserve).not.toHaveBeenCalled();
});

it('should recreate the observer when threshold, rootMargin, or root changes', async () => {
const root = document.createElement('div');
const { result, rerender } = await renderHookSSR(
(props: IntersectionObserverInit) => useIntersectionObserver(vi.fn(), props),
{ initialProps: { root: null, rootMargin: '0px', threshold: 0.5 } as IntersectionObserverInit }
);
const mockElement = document.createElement('div');

await act(async () => {
result.current(mockElement);
});
expect(IntersectionObserverSpy).toHaveBeenCalledTimes(1);

rerender({ root: null, rootMargin: '0px', threshold: [0, 0.5] });
expect(IntersectionObserverSpy).toHaveBeenCalledTimes(2);

rerender({ root: null, rootMargin: '10px', threshold: [0, 0.5] });
expect(IntersectionObserverSpy).toHaveBeenCalledTimes(3);

rerender({ root, rootMargin: '10px', threshold: [0, 0.5] });
expect(IntersectionObserverSpy).toHaveBeenCalledTimes(4);
});

it('should not recreate the observer when a new threshold array has the same values in the same order', async () => {
const { result, rerender } = await renderHookSSR(
(props: IntersectionObserverInit) => useIntersectionObserver(vi.fn(), props),
{ initialProps: { threshold: [0, 0.25, 0.5] } as IntersectionObserverInit }
);
const mockElement = document.createElement('div');

await act(async () => {
result.current(mockElement);
});
expect(IntersectionObserverSpy).toHaveBeenCalledTimes(1);

// A brand-new array instance with identical values must not be treated as a change.
rerender({ threshold: [0, 0.25, 0.5] });
expect(IntersectionObserverSpy).toHaveBeenCalledTimes(1);
expect(mockUnobserve).not.toHaveBeenCalled();

// Same values, different order: a real change, so it should recreate.
rerender({ threshold: [0.5, 0.25, 0] });
expect(IntersectionObserverSpy).toHaveBeenCalledTimes(2);
});
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useMemo } from 'react';

import { usePreservedCallback } from '../usePreservedCallback/index.ts';
import { usePreservedReference } from '../usePreservedReference/index.ts';
import { useRefEffect } from '../useRefEffect/index.ts';

/**
Expand Down Expand Up @@ -40,6 +41,7 @@ export function useIntersectionObserver<Element extends HTMLElement>(
options: IntersectionObserverInit
): (element: Element | null) => void {
const preservedCallback = usePreservedCallback(callback);
const preservedOptions = usePreservedReference(options, areIntersectionOptionsEqual);

const observer = useMemo(() => {
if (typeof IntersectionObserver === 'undefined') {
Expand All @@ -48,8 +50,8 @@ export function useIntersectionObserver<Element extends HTMLElement>(

return new IntersectionObserver(([entry]) => {
preservedCallback(entry);
}, options);
}, [preservedCallback, options]);
}, preservedOptions);
}, [preservedCallback, preservedOptions]);

return useRefEffect<Element>(
element => {
Expand All @@ -59,6 +61,16 @@ export function useIntersectionObserver<Element extends HTMLElement>(
observer?.unobserve(element);
};
},
[preservedCallback, options]
[preservedCallback, preservedOptions]
);
}

// `root` is a DOM node: `JSON.stringify` would collapse any node to `"{}"`, so it must be compared by reference.
// `threshold` can be an inline array (e.g. `threshold: [0, 0.5]`) that gets a new reference every render even
// though the values are unchanged, so it needs `JSON.stringify` instead of `===`. `rootMargin` is a plain
// string, so `===` already compares it by value.
function areIntersectionOptionsEqual(a: IntersectionObserverInit, b: IntersectionObserverInit): boolean {
return (
a.root === b.root && a.rootMargin === b.rootMargin && JSON.stringify(a.threshold) === JSON.stringify(b.threshold)
Comment on lines +67 to +74

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could you add a short comment here explaining why root is compared by reference while threshold goes through JSON.stringify? The reasoning is in the PR description, but it would be nice to have it right next to the code. 👍

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@hyesungoh
Thanks for the feedback! Pushed a fix in 84e4621.

Let me know if this reads clearly, or if you'd frame it differently — happy to iterate further. 😀

);
}
Loading