You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

56 lines
1.7 KiB

  1. import useCustomEffect from './useCustomEffect';
  2. import isEqual from "lodash-es/isEqual";
  3. import useImmediateUpdateEffect from './useImmediateUpdateEffect';
  4. import useEventCallback from './useEventCallback';
  5. function isDepsEqual(_ref, _ref2) {
  6. var nextElement = _ref[0],
  7. nextConfig = _ref[1];
  8. var prevElement = _ref2[0],
  9. prevConfig = _ref2[1];
  10. return nextElement === prevElement && isEqual(nextConfig, prevConfig);
  11. }
  12. /**
  13. * Observe mutations on a DOM node or tree of DOM nodes.
  14. * Depends on the `MutationObserver` api.
  15. *
  16. * ```ts
  17. * const [element, attachRef] = useCallbackRef(null);
  18. *
  19. * useMutationObserver(element, { subtree: true }, (records) => {
  20. *
  21. * });
  22. *
  23. * return (
  24. * <div ref={attachRef} />
  25. * )
  26. * ```
  27. *
  28. * @param element The DOM element to observe
  29. * @param config The observer configuration
  30. * @param callback A callback fired when a mutation occurs
  31. */
  32. function useMutationObserver(element, config, callback) {
  33. var fn = useEventCallback(callback);
  34. useCustomEffect(function () {
  35. if (!element) return; // The behavior around reusing mutation observers is confusing
  36. // observing again _should_ disable the last listener but doesn't
  37. // seem to always be the case, maybe just in JSDOM? In any case the cost
  38. // to redeclaring it is gonna be fairly low anyway, so make it simple
  39. var observer = new MutationObserver(fn);
  40. observer.observe(element, config);
  41. return function () {
  42. observer.disconnect();
  43. };
  44. }, [element, config], {
  45. isEqual: isDepsEqual,
  46. // Intentionally done in render, otherwise observer will miss any
  47. // changes made to the DOM during this update
  48. effectHook: useImmediateUpdateEffect
  49. });
  50. }
  51. export default useMutationObserver;