umami/src/components/hooks/useSticky.ts

27 lines
724 B
TypeScript
Raw Normal View History

2023-02-09 08:14:11 +01:00
import { useState, useEffect, useRef } from 'react';
2023-05-18 08:20:06 +02:00
export function useSticky({ enabled = true, threshold = 1 }) {
2023-03-22 22:05:55 +01:00
const [isSticky, setIsSticky] = useState(false);
2023-02-09 08:14:11 +01:00
const ref = useRef(null);
useEffect(() => {
2023-11-14 06:36:52 +01:00
let observer: IntersectionObserver | undefined;
const handler: IntersectionObserverCallback = ([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 };
}
2023-05-18 08:20:06 +02:00
export default useSticky;