Created
February 2, 2022 08:20
-
-
Save fredrikbergqvist/35b09d41306e38f7ec1dc4a00998ec14 to your computer and use it in GitHub Desktop.
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"; | |
export const useIntersectionObserver = ( | |
callback: (unknown) => unknown, | |
options = { | |
root: null, | |
threshold: 0.1, | |
rootMargin: "0px", | |
}, | |
reference: HTMLElement | null = null, | |
additionalDependencies: unknown[] = [] | |
): void => { | |
const dependencyArray = [callback, reference, ...additionalDependencies]; | |
useEffect(() => { | |
const observer = new IntersectionObserver(callback, options); | |
if (reference) { | |
observer.observe(reference); | |
} | |
return () => { | |
if (reference) { | |
observer.unobserve(reference); | |
} | |
}; | |
}, dependencyArray); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment