mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
Also reduce max line width to 100. And remove `lint:types` step for commit sequence, it bothers when committing incomplete (wip) changes.
33 lines
922 B
TypeScript
33 lines
922 B
TypeScript
import { RefObject, useEffect, useState } from 'react';
|
|
|
|
const useIntersection = (
|
|
ref: RefObject<HTMLElement>,
|
|
options: IntersectionObserverInit
|
|
): IntersectionObserverEntry | null => {
|
|
const [
|
|
intersectionObserverEntry,
|
|
setIntersectionObserverEntry,
|
|
] = useState<IntersectionObserverEntry | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (ref.current && typeof IntersectionObserver === 'function') {
|
|
const handler = (entries: IntersectionObserverEntry[]) => {
|
|
setIntersectionObserverEntry(entries[0]);
|
|
};
|
|
|
|
const observer = new IntersectionObserver(handler, options);
|
|
observer.observe(ref.current);
|
|
|
|
return () => {
|
|
setIntersectionObserverEntry(null);
|
|
observer.disconnect();
|
|
};
|
|
}
|
|
return () => {};
|
|
}, [ref.current, options.threshold, options.root, options.rootMargin]);
|
|
|
|
return intersectionObserverEntry;
|
|
};
|
|
|
|
export default useIntersection;
|