Last active
June 10, 2022 12:27
-
-
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.
This file contains 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, 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