Skip to content

Instantly share code, notes, and snippets.

@Sachin-chaurasiya
Last active June 10, 2022 12:27
Show Gist options
  • Save Sachin-chaurasiya/941c4963df220d1a4cd5befb28818bd0 to your computer and use it in GitHub Desktop.
Save Sachin-chaurasiya/941c4963df220d1a4cd5befb28818bd0 to your computer and use it in GitHub Desktop.
Use this hook to check if element is in viewport or not.
import { useEffect, useRef, useState } from 'react';
export const useElementInView = (options) => {
const elementRef = useRef(null);
const [isInView, setIsInView] = useState(false);
const handleObserve = (entries) => {
const [entry] = entries;
setIsInView(entry.isIntersecting);
};
useEffect(() => {
const observer = new IntersectionObserver(handleObserve, options);
if (elementRef.current) {
observer.observe(elementRef.current);
}
return () => {
if (elementRef.current) {
observer.unobserve(elementRef.current);
}
};
}, [elementRef, options]);
return [elementRef, isInView];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment