rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
40 lines (39 loc) • 1.26 kB
JavaScript
import { useEffect, useCallback, useState } from "react";
import { noop } from "../utils/noop";
var config = {
attributes: true,
characterData: true,
childList: true,
subtree: 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
* @see https://react-hooks.org/docs/useMutationObserverRef
*/
function useMutationObserverRef(callback, options) {
if (options === void 0) { options = config; }
var _a = useState(null), node = _a[0], setNode = _a[1];
useEffect(function () {
// Create an observer instance linked to the callback function
if (node) {
var observer_1 = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer_1.observe(node, options);
return function () {
observer_1.disconnect();
};
}
return noop;
}, [node, callback, options]);
var ref = useCallback(function (nodeElement) {
setNode(nodeElement);
}, []);
return [ref];
}
export { useMutationObserverRef };