Created
March 22, 2023 14:07
-
-
Save louis-young/45b3aefcd3f5be69c93aabb78750a6e1 to your computer and use it in GitHub Desktop.
useIntersectionObserver
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 { useEffect } from "react"; | |
import type { UseIntersectionObserverParameters } from "./types"; | |
export const useIntersectionObserver = ({ | |
observableRef, | |
callback, | |
options, | |
}: UseIntersectionObserverParameters) => { | |
useEffect(() => { | |
const intersectionObserver = new IntersectionObserver( | |
([{ isIntersecting }]) => { | |
if (isIntersecting) { | |
callback(); | |
} | |
}, | |
{ | |
rootMargin: "500px", | |
threshold: 0, | |
...options, | |
} | |
); | |
if (observableRef.current) { | |
intersectionObserver.observe(observableRef.current); | |
} | |
return () => { | |
if (observableRef.current) { | |
intersectionObserver.unobserve(observableRef.current); | |
} | |
}; | |
}, [callback]); | |
}; |
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 type { RefObject } from "react"; | |
export interface UseIntersectionObserverParameters { | |
observableRef: RefObject<HTMLElement>; | |
callback: () => void; | |
options?: IntersectionObserverInit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment