aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-mutation-observer/use-mutation-observer.ts
blob: 6043055b00374a11d43538ea7af793e4ec497931 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { type RefObject, useEffect } from 'react';
import type { Nullable } from '../../../types';

type UseMutationObserverProps<T extends Nullable<HTMLElement>> = {
  /**
   * A callback to execute when mutations are observed.
   */
  callback: MutationCallback;
  /**
   * The options passed to mutation observer.
   */
  options: MutationObserverInit;
  /**
   * A reference to the DOM node to observe.
   */
  ref: RefObject<T>;
};

export const useMutationObserver = <T extends Nullable<HTMLElement>>({
  callback,
  options,
  ref,
}: UseMutationObserverProps<T>) => {
  useEffect(() => {
    if (!ref.current) return undefined;

    const observer = new MutationObserver(callback);

    observer.observe(ref.current, options);

    return () => {
      observer.disconnect();
    };
  }, [callback, options, ref]);
};