Skip to content

Instantly share code, notes, and snippets.

@namikingsoft
Created December 3, 2022 10:26
Show Gist options
  • Save namikingsoft/940061b29e80ddbf3a273032ca2c7b49 to your computer and use it in GitHub Desktop.
Save namikingsoft/940061b29e80ddbf3a273032ca2c7b49 to your computer and use it in GitHub Desktop.
use-intersection
import { useEffect, useState } from 'react'
type ReturnType = {
setRef: (elm: Element | null) => void
done: boolean
}
export const useIntersection = (): ReturnType => {
const [element, setElement] = useState<Element | null>(null)
const [done, setDone] = useState(false)
useEffect(() => {
if (element) {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting && entry.target === element) {
observer.unobserve(element)
setDone(true)
}
})
},
{
rootMargin: '-25% 0px',
threshold: 0,
},
)
observer.observe(element)
return () => {
observer.disconnect()
}
}
}, [element])
return { done, setRef: setElement }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment