Skip to content

Instantly share code, notes, and snippets.

@thepuskar
Created July 31, 2023 06:36
Show Gist options
  • Save thepuskar/7ceddcd1055a56e3903fd1ede38e79eb to your computer and use it in GitHub Desktop.
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
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