Skip to content

Instantly share code, notes, and snippets.

@pffigueiredo
Created April 16, 2021 17:20
Show Gist options
  • Save pffigueiredo/8d0b342b300699fe3894afaf390277a1 to your computer and use it in GitHub Desktop.
Save pffigueiredo/8d0b342b300699fe3894afaf390277a1 to your computer and use it in GitHub Desktop.
React hook to check if some element is currently on the view port
import { RefObject, useEffect, useState } from 'react';
import throttle from 'utils/throttle';
export default function useOnScreen(
elementRef: RefObject<HTMLElement>
): boolean {
const [isVisible, setIsVisible] = useState(false);
const onScroll = throttle(() => {
if (!elementRef.current) {
setIsVisible(false);
return;
}
const { top } = elementRef.current.getBoundingClientRect();
setIsVisible(top >= 0 && top <= window.innerHeight);
}, 200);
useEffect(() => {
document.addEventListener('scroll', onScroll, true);
return () => document.removeEventListener('scroll', onScroll, true);
});
return isVisible;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment