Created
January 16, 2023 13:44
-
-
Save maiconrs95/4a97e9eb06f6c9196b1ff682eb7f3a7d to your computer and use it in GitHub Desktop.
React Intersection observer hook
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 { useCallback, useState } from 'react'; | |
import * as React from 'react'; | |
type Result = { | |
measureRef: (node: unknown) => void; | |
isIntersecting: boolean; | |
observer?: IntersectionObserver; | |
}; | |
function useOnScreen({ root = null, rootMargin = '0px', threshold = 0 } = {}): Result { | |
const [observer, setOserver] = useState<IntersectionObserver>(); | |
const [isIntersecting, setIntersecting] = useState(false); | |
React.useEffect(() => { | |
return () => { | |
if (observer) { | |
observer.disconnect(); | |
} | |
}; | |
}, [observer]); | |
const measureRef = useCallback( | |
node => { | |
if (node) { | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
setIntersecting(entry.isIntersecting); | |
}, | |
{ root, rootMargin, threshold } | |
); | |
observer.observe(node); | |
setOserver(observer); | |
} | |
}, | |
[root, rootMargin, threshold] | |
); | |
return { measureRef, isIntersecting, observer }; | |
} | |
export default useOnScreen; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment