Created
June 7, 2019 08:28
-
-
Save yongdamsh/924c2a7a5b8da317df7331ed204bcc21 to your computer and use it in GitHub Desktop.
React custom hook based on intersectionObserver
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
| import 'intersection-observer'; | |
| import { useCallback, useState, useEffect, useRef } from 'react'; | |
| const defaultEntry = { | |
| isIntersecting: false, | |
| intersectionRatio: 0 | |
| }; | |
| const defaultOptions = {}; | |
| function useElementVisibility(options = defaultOptions) { | |
| const ref = useRef(null); | |
| const [visibility, setVisibility] = useState(defaultEntry); | |
| function getObserver() { | |
| if (ref.current === null) { | |
| ref.current = new window.IntersectionObserver(entries => { | |
| entries.forEach(entry => { | |
| setVisibility(entry); | |
| }); | |
| }, options); | |
| } | |
| return ref.current; | |
| } | |
| const observer = getObserver(); | |
| const subscribe = useCallback( | |
| node => { | |
| if (node) { | |
| observer.observe(node); | |
| } | |
| }, | |
| [observer] | |
| ); | |
| const unsubscribe = () => observer.disconnect(); | |
| useEffect(() => { | |
| return () => { | |
| observer.disconnect(); | |
| }; | |
| }, [observer]); | |
| return [visibility, subscribe, unsubscribe]; | |
| } | |
| export default useElementVisibility; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment