Last active
August 30, 2022 05:37
-
-
Save luigircruz/f7bd9381834524e6395724017225c0ec to your computer and use it in GitHub Desktop.
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
| /* | |
| Is a given element currently in the viewport? | |
| This hook tracks that information using | |
| IntersectionObserver. | |
| */ | |
| import { useState, useEffect } from 'react'; | |
| function useIsOnscreen( | |
| elementRef, | |
| defaultState = false | |
| ) { | |
| const [isOnscreen, setIsOnscreen] = useState(defaultState); | |
| useEffect(() => { | |
| if (!elementRef.current) { | |
| return null; | |
| } | |
| const observer = new window.IntersectionObserver( | |
| (entries, observer) => { | |
| const [entry] = entries; | |
| setIsOnscreen(entry.intersectionRatio > 0); | |
| } | |
| ); | |
| observer.observe(elementRef.current); | |
| return () => { | |
| observer.disconnect(); | |
| }; | |
| }, [elementRef]); | |
| return isOnscreen; | |
| } | |
| export default useIsOnscreen; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment