ahooks
Version:
react hooks library
19 lines (18 loc) • 730 B
JavaScript
import { getTargetElement } from '../utils/domTarget';
import useDeepCompareEffectWithTarget from '../utils/useDeepCompareWithTarget';
import useLatest from '../useLatest';
const useMutationObserver = (callback, target, options = {}) => {
const callbackRef = useLatest(callback);
useDeepCompareEffectWithTarget(() => {
const element = getTargetElement(target);
if (!element) {
return;
}
const observer = new MutationObserver(callbackRef.current);
observer.observe(element, options);
return () => {
observer === null || observer === void 0 ? void 0 : observer.disconnect();
};
}, [options], target);
};
export default useMutationObserver;