UNPKG

@boomerang-io/utils

Version:

A library of reusable utilities and hooks for React webapps on the Boomerang platform.

36 lines (33 loc) 1.12 kB
//Source: https://github.com/imbhargav5/rooks/blob/master/packages/shared/useMutationObserver.ts import { useEffect } from "react"; const config = { attributes: true, characterData: true, subtree: true, childList: true }; /** * * useMutationObserver hook * * Returns a mutation observer for a React Ref and fires a callback * * @param {MutableRefObject<HTMLElement | null>} ref React ref on which mutations are to be observed * @param {MutationCallback} callback Function that needs to be fired on mutation * @param {MutationObserverInit} options */ function useMutationObserver(ref, callback) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : config; useEffect(() => { // Create an observer instance linked to the callback function if (ref.current) { const observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(ref.current, options); return () => { observer.disconnect(); }; } }, [callback, options, ref]); } export default useMutationObserver;