consolelog.tools logo

Intersection Observer Generator

Generate Intersection Observer API code for different frameworks

Configuration

Generated Code

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>
  );
}

Presets

Was this tool helpful?

Share Your Experience

Help others discover this tool!

Frequently Asked Questions - Intersection Observer Generator