useIsStuck.tsx 638 B

123456789101112131415161718192021222324252627282930
  1. import 'intersection-observer'; // polyfill
  2. import {useEffect, useState} from 'react';
  3. /**
  4. * Determine if a element with `position: sticky` is currently stuck.
  5. */
  6. export function useIsStuck(el: HTMLElement | null) {
  7. const [isStuck, setIsStuck] = useState(false);
  8. useEffect(() => {
  9. if (el === null) {
  10. return () => {};
  11. }
  12. const observer = new IntersectionObserver(
  13. ([entry]) => setIsStuck(entry.intersectionRatio < 1),
  14. {
  15. rootMargin: '-1px 0px 0px 0px',
  16. threshold: [1],
  17. }
  18. );
  19. observer.observe(el);
  20. return () => observer.disconnect();
  21. }, [el]);
  22. return isStuck;
  23. }