useInView

Detect if an element is currently visible in the viewport.


✅ Features

  • Based on IntersectionObserver API
  • Lazy-load content, trigger animations, etc.
  • Optional rootMargin and threshold

📦 Usage

1import { useInView } from './useInView';
2
3const ref = useRef(null);
4const isVisible = useInView(ref, { threshold: 0.5 });
5
6return (
7  <div ref={ref}>
8    {isVisible ? "I'm in view!" : "Scroll down to see me."}
9  </div>
10);

📋 Source Code

This is the full implementation of useInView

1import { useState, useEffect, RefObject } from 'react';
2
3export function useInView(ref: RefObject<Element>, rootMargin: string = '0px'): boolean {
4  const [isInView, setIsInView] = useState(false);
5
6  useEffect(() => {
7    const observer = new IntersectionObserver(
8      ([entry]) => setIsInView(entry.isIntersecting),
9      { rootMargin }
10    );
11
12    const el = ref.current;
13    if (el) observer.observe(el);
14
15    return () => el && observer.unobserve(el);
16  }, [ref, rootMargin]);
17
18  return isInView;
19}
20