aboutsummaryrefslogtreecommitdiff
path: root/src/components/hooks/useSticky.ts
blob: ef9fb36f3c1802034005e88ce362c9fa95cad472 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { useEffect, useRef, useState } from 'react';

export function useSticky({ enabled = true, threshold = 1 }) {
  const [isSticky, setIsSticky] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    let observer: IntersectionObserver | undefined;
    // eslint-disable-next-line no-undef
    const handler: IntersectionObserverCallback = ([entry]) =>
      setIsSticky(entry.intersectionRatio < threshold);

    if (enabled && ref.current) {
      observer = new IntersectionObserver(handler, { threshold: [threshold] });
      observer.observe(ref.current);
    }
    return () => {
      if (observer) {
        observer.disconnect();
      }
    };
  }, [ref, enabled, threshold]);

  return { ref, isSticky };
}