From e924061c543c61e9eaf01fa72736b08141bdfe0a Mon Sep 17 00:00:00 2001 From: Marshall Polaris Date: Fri, 2 Sep 2022 19:39:07 -0700 Subject: [PATCH] Don't re-create visibility observer for no reason (#849) * Don't re-create visibility observer for no reason * `IntersectionObserver.unobserve` instead of `.disconnect` --- web/components/visibility-observer.tsx | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/web/components/visibility-observer.tsx b/web/components/visibility-observer.tsx index 9af410c7..aea2e41d 100644 --- a/web/components/visibility-observer.tsx +++ b/web/components/visibility-observer.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { useEvent } from '../hooks/use-event' export function VisibilityObserver(props: { @@ -8,17 +8,18 @@ export function VisibilityObserver(props: { const { className } = props const [elem, setElem] = useState(null) const onVisibilityUpdated = useEvent(props.onVisibilityUpdated) - - useEffect(() => { - const hasIOSupport = !!window.IntersectionObserver - if (!hasIOSupport || !elem) return - - const observer = new IntersectionObserver(([entry]) => { + const observer = useRef( + new IntersectionObserver(([entry]) => { onVisibilityUpdated(entry.isIntersecting) }, {}) - observer.observe(elem) - return () => observer.disconnect() - }, [elem, onVisibilityUpdated]) + ).current + + useEffect(() => { + if (elem) { + observer.observe(elem) + return () => observer.unobserve(elem) + } + }, [elem, observer]) return
}