useInView

使用 IntersectionObserver API 用於檢測元素是否在螢幕可見範圍內,並且提供相關的 callback。

JSX
import { useState, useEffect, useRef } from 'react';

export default function useInView(options) {
  const ref = useRef();
  const [isVisible, setIntersectionState] = useState(null);

  const intersectionCallback = (entries) => {
    const [entry] = entries;
    setIntersectionState(entry.isIntersecting);
  };

  useEffect(() => {
    const observer = new IntersectionObserver(intersectionCallback, {
      ...options,
      rootMargin: '0px 0px -100px 0px',
    });

    if (ref.current) observer.observe(ref?.current);

    return () => {
      observer.disconnect();
    };
  }, [ref, options]);

  return { isVisible, ref };
}
JSX
const App = () => {
  const { ref, isVisible } = useInView();
  return (
    <div>
      // some content
      <div ref={ref}>{isVisible ? 'The content is visible' : 'The content is not visible'}</div>
    </div>
  );
};
Last Updated: