@rooks/use-mutation-observer-ref
Version:
A hook that tracks mutations of an element. It returns a callbackRef.
45 lines (41 loc) • 1.54 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
typeof define === 'function' && define.amd ? define(['react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.useMutationObserverRef = factory(global.React));
}(this, (function (react) { 'use strict';
var config = {
attributes: true,
characterData: true,
subtree: true,
childList: true
};
/**
*
* useMutationObserverRef hook
*
* Returns a mutation observer for a React Ref and fires a callback
*
* @param {MutationCallback} callback Function that needs to be fired on mutation
* @param {MutationObserverInit} options
*/
function useMutationObserverRef(callback, options = config) {
const [node, setNode] = react.useState(null);
react.useEffect(() => {
// Create an observer instance linked to the callback function
if (node) {
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(node, options);
return () => {
observer.disconnect();
};
}
}, [node, callback, options]);
const ref = react.useCallback((node) => {
setNode(node);
}, []);
return [ref];
}
return useMutationObserverRef;
})));
//# sourceMappingURL=index.js.map