Created
February 12, 2023 06:37
-
-
Save Tim-W-James/a750c8a3b53e6bbe0ba22ac1cfe314a4 to your computer and use it in GitHub Desktop.
React useIntersectionObserver Custom Hook #hooks
This file contains hidden or 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 { RefObject, useEffect, useState } from "react"; | |
| const useIntersectionObserver = ( | |
| ref: RefObject<Element>, | |
| rootMargin = "0px" | |
| ): boolean => { | |
| const [isVisible, setIsVisible] = useState(false); | |
| useEffect(() => { | |
| const current = ref.current; | |
| if (current == null) { | |
| return; | |
| } | |
| const observer = new IntersectionObserver( | |
| ([entry]) => setIsVisible(entry?.isIntersecting || false), | |
| { rootMargin } | |
| ); | |
| observer.observe(current); | |
| return () => { | |
| observer.unobserve(current); | |
| }; | |
| }, [ref, rootMargin]); | |
| return isVisible; | |
| }; | |
| export default useIntersectionObserver; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment