diff --git a/src/useIntersection.ts b/src/useIntersection.ts index 4a7b78eaca..531ce3fbf7 100644 --- a/src/useIntersection.ts +++ b/src/useIntersection.ts @@ -15,14 +15,10 @@ const useIntersection = ( const observer = new IntersectionObserver(handler, options); observer.observe(ref.current); - return () => { - if (ref.current) { - observer.disconnect(); - } - }; + return () => observer.disconnect(); } return () => {}; - }, [ref, options.threshold, options.root, options.rootMargin]); + }, [ref.current, options.threshold, options.root, options.rootMargin]); return intersectionObserverEntry; }; diff --git a/tests/useIntersection.test.tsx b/tests/useIntersection.test.tsx index fb83108b46..b8cdde7bf9 100644 --- a/tests/useIntersection.test.tsx +++ b/tests/useIntersection.test.tsx @@ -8,6 +8,10 @@ import { useIntersection } from '../src'; beforeEach(() => { intersectionObserver.mock(); + const IO = IntersectionObserver; + jest.spyOn(IO.prototype, 'disconnect'); + jest.spyOn(global as any, 'IntersectionObserver'); + IntersectionObserver.prototype = IO.prototype; }); afterEach(() => { @@ -45,6 +49,22 @@ describe('useIntersection', () => { expect(result.current).toBe(null); }); + it('should disconnect an old IntersectionObserver instance when the ref changes', () => { + targetRef = createRef(); + targetRef.current = document.createElement('div'); + + const { rerender } = renderHook(() => useIntersection(targetRef, {})); + + targetRef.current = document.createElement('div'); + rerender(); + + targetRef.current = null; + rerender(); + + expect(IntersectionObserver).toHaveBeenCalledTimes(2); + expect(IntersectionObserver.prototype.disconnect).toHaveBeenCalledTimes(2); + }); + it('should return the first IntersectionObserverEntry when the IntersectionObserver registers an intersection', () => { TestUtils.act(() => { targetRef = createRef();