@momentum-ui/react-collaboration
Version:
Cisco Momentum UI Framework for React Collaboration Applications
39 lines • 1.67 kB
JavaScript
import { useEffect, useState } from 'react';
var DEFAULT_OPTIONS = {
attributes: false,
childList: true,
subtree: true,
};
/**
* This custom hooks abstracts the usage of the Mutation Observer with React components.
* Watch for changes being made to the DOM tree and trigger a custom callback.
*
* Note: with debounce the intermediate MutationRecords will be lost
*
* @param targetEl Observed DOM element
* @param callback Mutation callback
* @param config Mutation Observer config and other config
*
* @link https://blog.logrocket.com/guide-to-custom-react-hooks-with-mutationobserver/
*/
export var useMutationObservable = function (targetEl, callback, config) {
if (config === void 0) { config = DEFAULT_OPTIONS; }
var _a = useState(null), observer = _a[0], setObserver = _a[1];
useEffect(function () {
// disconnect previous observer here to make sure
// the old observer is disconnected in time (because between
// this useEffect and the useEffect below might have a time gap)
observer === null || observer === void 0 ? void 0 : observer.disconnect();
setObserver(function () { return new MutationObserver(callback); });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback, config]);
useEffect(function () {
if (targetEl) {
observer === null || observer === void 0 ? void 0 : observer.observe(targetEl, config);
}
return function () {
observer === null || observer === void 0 ? void 0 : observer.disconnect();
};
}, [observer, targetEl, config]);
};
//# sourceMappingURL=useMutationObservable.js.map