UNPKG

@fremtind/jkl-react-hooks

Version:
28 lines (27 loc) 848 B
import { useEffect, useRef } from "react"; const hasWindowWithMutationObserver = () => typeof window !== "undefined" && typeof MutationObserver !== "undefined"; const useMutationObserver = (targetRef, onObservation, config) => { const observerRef = useRef(null); useEffect(() => { let observer = observerRef.current; if (hasWindowWithMutationObserver()) { const target = targetRef.current; if (observer) { observer.disconnect(); } observer = new MutationObserver(onObservation); if (target) { observer.observe(target, config); } } return () => { if (hasWindowWithMutationObserver() && observer) { observer.disconnect(); } }; }, [targetRef, onObservation, config]); }; export { useMutationObserver }; //# sourceMappingURL=useMutationObserver.js.map