teableio/teable

View on GitHub
apps/nextjs-app/src/features/app/blocks/view/kanban/hooks/useInView.ts

Summary

Maintainability
A
0 mins
Test Coverage
import type { RefObject } from 'react';
import { useState, useEffect, useRef } from 'react';

export const useInView = (options = {}): [RefObject<HTMLDivElement>, boolean] => {
  const [isInView, setIsInView] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        setIsInView(entry.isIntersecting);
      },
      { ...options }
    );

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      if (ref.current) {
        observer.unobserve(ref.current);
      }
    };
  }, [ref, options]);

  return [ref, isInView];
};