//=== 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;
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.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.