Skip to content

Instantly share code, notes, and snippets.

@ali-sabry
Last active April 5, 2023 04:48
Show Gist options
  • Save ali-sabry/038ea2cecaccf311cfd695abc0d69eb1 to your computer and use it in GitHub Desktop.
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.
//=== 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