Created
December 3, 2022 10:26
-
-
Save namikingsoft/940061b29e80ddbf3a273032ca2c7b49 to your computer and use it in GitHub Desktop.
use-intersection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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