2023-02-06 13:39:17 -08:00
|
|
|
import React, { useEffect, useMemo, useState } from 'react';
|
2022-03-23 05:40:21 -07:00
|
|
|
|
2023-02-06 13:39:17 -08:00
|
|
|
/** Detect whether a given element is on the screen. */
|
|
|
|
// https://stackoverflow.com/a/64892655
|
|
|
|
export const useOnScreen = <T>(ref: React.RefObject<T & Element>) => {
|
|
|
|
const [isIntersecting, setIntersecting] = useState(false);
|
2022-03-23 05:40:21 -07:00
|
|
|
|
2023-02-06 13:39:17 -08:00
|
|
|
const observer = useMemo(() => {
|
|
|
|
return new IntersectionObserver(
|
|
|
|
([entry]) => setIntersecting(entry.isIntersecting),
|
|
|
|
);
|
|
|
|
}, []);
|
2022-03-23 05:40:21 -07:00
|
|
|
|
2023-02-06 13:39:17 -08:00
|
|
|
useEffect(() => {
|
2022-03-24 08:06:01 -07:00
|
|
|
if (ref.current) {
|
|
|
|
observer.observe(ref.current);
|
|
|
|
}
|
2022-03-23 05:40:21 -07:00
|
|
|
|
|
|
|
return () => {
|
|
|
|
observer.disconnect();
|
|
|
|
};
|
2022-03-24 08:06:01 -07:00
|
|
|
}, [ref.current]);
|
2022-03-23 05:40:21 -07:00
|
|
|
|
|
|
|
return isIntersecting;
|
|
|
|
};
|