Don't re-create visibility observer for no reason (#849)
* Don't re-create visibility observer for no reason * `IntersectionObserver.unobserve` instead of `.disconnect`
This commit is contained in:
parent
25a0276bf7
commit
e924061c54
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useEvent } from '../hooks/use-event'
|
import { useEvent } from '../hooks/use-event'
|
||||||
|
|
||||||
export function VisibilityObserver(props: {
|
export function VisibilityObserver(props: {
|
||||||
|
@ -8,17 +8,18 @@ export function VisibilityObserver(props: {
|
||||||
const { className } = props
|
const { className } = props
|
||||||
const [elem, setElem] = useState<HTMLElement | null>(null)
|
const [elem, setElem] = useState<HTMLElement | null>(null)
|
||||||
const onVisibilityUpdated = useEvent(props.onVisibilityUpdated)
|
const onVisibilityUpdated = useEvent(props.onVisibilityUpdated)
|
||||||
|
const observer = useRef(
|
||||||
useEffect(() => {
|
new IntersectionObserver(([entry]) => {
|
||||||
const hasIOSupport = !!window.IntersectionObserver
|
|
||||||
if (!hasIOSupport || !elem) return
|
|
||||||
|
|
||||||
const observer = new IntersectionObserver(([entry]) => {
|
|
||||||
onVisibilityUpdated(entry.isIntersecting)
|
onVisibilityUpdated(entry.isIntersecting)
|
||||||
}, {})
|
}, {})
|
||||||
observer.observe(elem)
|
).current
|
||||||
return () => observer.disconnect()
|
|
||||||
}, [elem, onVisibilityUpdated])
|
useEffect(() => {
|
||||||
|
if (elem) {
|
||||||
|
observer.observe(elem)
|
||||||
|
return () => observer.unobserve(elem)
|
||||||
|
}
|
||||||
|
}, [elem, observer])
|
||||||
|
|
||||||
return <div ref={setElem} className={className}></div>
|
return <div ref={setElem} className={className}></div>
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user