umami/hooks/useSticky.js

24 lines
635 B
JavaScript
Raw Normal View History

2023-02-09 08:14:11 +01:00
import { useState, useEffect, useRef } from 'react';
2023-03-22 22:05:55 +01:00
export default function useSticky({ enabled = true, threshold = 1 }) {
const [isSticky, setIsSticky] = useState(false);
2023-02-09 08:14:11 +01:00
const ref = useRef(null);
useEffect(() => {
2023-03-22 09:53:34 +01:00
let observer;
2023-03-22 22:05:55 +01:00
const handler = ([entry]) => setIsSticky(entry.intersectionRatio < threshold);
2023-02-09 08:14:11 +01:00
2023-03-22 09:53:34 +01:00
if (enabled && ref.current) {
2023-03-22 22:05:55 +01:00
observer = new IntersectionObserver(handler, { threshold: [threshold] });
2023-03-22 09:53:34 +01:00
observer.observe(ref.current);
2023-02-09 17:22:36 +01:00
}
2023-02-09 08:14:11 +01:00
return () => {
2023-03-22 09:53:34 +01:00
if (observer) {
observer.disconnect();
}
2023-02-09 08:14:11 +01:00
};
2023-03-22 22:05:55 +01:00
}, [ref, enabled, threshold]);
2023-02-09 08:14:11 +01:00
return { ref, isSticky };
}