umami/hooks/useSticky.js

24 lines
615 B
JavaScript
Raw Normal View History

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