Last active
April 5, 2023 04:48
-
-
Save ali-sabry/038ea2cecaccf311cfd695abc0d69eb1 to your computer and use it in GitHub Desktop.
The useIntersectionObserver react custom Hook enables detection of an element's visibility on the screen, allowing for lazy loading of content like images, improving page load times and performance.
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
//=== Craete The Custom Hook | |
import { useState, useEffect } from 'react'; | |
const useIntersectionObserver = (ref, options) => { | |
const [isIntersecting, setIsIntersecting] = useState(false); | |
useEffect(() => { | |
const observer = new IntersectionObserver(([entry]) => { | |
setIsIntersecting(entry.isIntersecting); | |
}, options); | |
if (ref.current) { | |
observer.observe(ref.current); | |
} | |
return () => { | |
if (ref.current) { | |
observer.unobserve(ref.current); | |
} | |
}; | |
}, [ref, options]); | |
return isIntersecting; | |
}; | |
export default useIntersectionObserver; | |
//=== Use The Custom Hook | |
import { useRef } from 'react'; | |
import { useIntersectionObserver } from './useIntersectionObserver'; | |
const App = ()=> { | |
const targetRef = useRef(null); | |
const isTargetVisible = useIntersectionObserver(targetRef, { threshold: 0.5 }); | |
return ( | |
<div ref={targetRef}> | |
{isTargetVisible ? <p>Target element is visible!</p> : <p>show the next element</p>} | |
</div> | |
) | |
}; | |
export default App; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment