import { useRef, useCallback } from "react";

const useObserverWithRefCallback = (cb?: () => void, runMore = true) => {
	const observer = useRef<IntersectionObserver | null>(null);
	const setRef = useCallback(
		(node: HTMLElement) => {
			if (observer.current) observer.current.disconnect();
			if (node && runMore && cb) {
				observer.current = new IntersectionObserver((enteries) => {
					if (enteries[0].isIntersecting) cb();
				});
				observer.current.observe(node);
			}
		},
		[runMore, cb]
	);

	return setRef;
};

export default useObserverWithRefCallback;
