Generate Intersection Observer API code for different frameworks
import { useEffect, useRef, useState } from 'react';
export function useIntersectionObserver(options = {}) {
const [isIntersecting, setIsIntersecting] = useState(false);
const [hasIntersected, setHasIntersected] = useState(false);
const targetRef = useRef(null);
useEffect(() => {
const target = targetRef.current;
if (!target) return;
const observer = new IntersectionObserver(
([entry]) => {
setIsIntersecting(entry.isIntersecting);
if (entry.isIntersecting) {
setHasIntersected(true);
observer.disconnect();
}
},
{
root: null,
rootMargin: '0px',
threshold: 0.3,
...options
}
);
observer.observe(target);
return () => {
observer.disconnect();
};
}, []);
return { targetRef, isIntersecting, hasIntersected };
}
// Usage example:
export default function AnimatedComponent() {
const { targetRef, isIntersecting, hasIntersected } = useIntersectionObserver();
return (
<div
ref={targetRef}
className={`element ${hasIntersected ? 'visible' : ''}`}
>
Your content here
</div>
);
}Help others discover this tool!