From 3f8687e1f51cc48efbf6be3f0677f5bd06ecba08 Mon Sep 17 00:00:00 2001 From: dizel3d Date: Tue, 28 Jan 2020 00:24:34 +0300 Subject: [PATCH] fix(useIntersection): reset an intersectionObserverEntry when the ref changes --- src/useIntersection.ts | 5 ++++- tests/useIntersection.test.tsx | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/useIntersection.ts b/src/useIntersection.ts index 531ce3fb..aec578f4 100644 --- a/src/useIntersection.ts +++ b/src/useIntersection.ts @@ -15,7 +15,10 @@ const useIntersection = ( const observer = new IntersectionObserver(handler, options); observer.observe(ref.current); - return () => observer.disconnect(); + return () => { + setIntersectionObserverEntry(null); + observer.disconnect(); + }; } return () => {}; }, [ref.current, options.threshold, options.root, options.rootMargin]); diff --git a/tests/useIntersection.test.tsx b/tests/useIntersection.test.tsx index b8cdde7b..cdd3d9e8 100644 --- a/tests/useIntersection.test.tsx +++ b/tests/useIntersection.test.tsx @@ -49,6 +49,35 @@ describe('useIntersection', () => { expect(result.current).toBe(null); }); + it('should reset an intersectionObserverEntry when the ref changes', () => { + TestUtils.act(() => { + targetRef = createRef(); + ReactDOM.render(
, container); + }); + + const { result, rerender } = renderHook(() => useIntersection(targetRef, { root: container, threshold: 0.8 })); + + const mockIntersectionObserverEntry = { + boundingClientRect: targetRef.current.getBoundingClientRect(), + intersectionRatio: 0.81, + intersectionRect: container.getBoundingClientRect(), + isIntersecting: true, + rootBounds: container.getBoundingClientRect(), + target: targetRef.current, + time: 300, + }; + TestRenderer.act(() => { + intersectionObserver.simulate(mockIntersectionObserverEntry); + }); + + expect(result.current).toEqual(mockIntersectionObserverEntry); + + targetRef.current = document.createElement('div'); + rerender(); + + expect(result.current).toEqual(null); + }); + it('should disconnect an old IntersectionObserver instance when the ref changes', () => { targetRef = createRef(); targetRef.current = document.createElement('div');