Created
July 31, 2023 06:36
-
-
Save thepuskar/7ceddcd1055a56e3903fd1ede38e79eb to your computer and use it in GitHub Desktop.
The `useOnScreen` function is a custom React hook that detects whether a given element is currently visible on the scree
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, useMemo, useState,RefObject } from "react"; | |
export function useOnScreen(ref:RefObject<HTMLElement>):boolean { | |
const [isOnScreen, setIsOnScreen] = useState<boolean>(false); | |
const observer = useMemo( | |
() => new IntersectionObserver(([entry]) => setIsOnScreen(entry.isIntersecting)), | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
[ref] | |
); | |
useEffect(() => { | |
observer.observe(ref.current); | |
return () => observer.disconnect(); | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []); | |
return isOnScreen; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment