From 0043ec2e18043fac6546b2a751e9a1677789c437 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Sun, 7 Nov 2021 17:56:32 +0200 Subject: [PATCH] Add useMutationObserver --- snippets/useMutationObserver.md | 78 +++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 snippets/useMutationObserver.md diff --git a/snippets/useMutationObserver.md b/snippets/useMutationObserver.md new file mode 100644 index 000000000..a5a75fcca --- /dev/null +++ b/snippets/useMutationObserver.md @@ -0,0 +1,78 @@ +--- +title: useMutationObserver +tags: hooks,effect,intermediate +firstSeen: 2021-11-23T05:00:00-04:00 +--- + +Watches for changes made to the DOM tree, using a `MutationObserver` + +- Use a `useEffect()` hook that depends on the values of `callback` and `options`. +- Check if the given `ref` is initialized. If it is, create a new `MutationObserver` and pass it the `callback`. +- Call `MutationObserver.observe()` with the given `options` to watch the given `ref` for changes. +- Use `MutationObserver.disconnect()` to remove the observer from the `ref` when the component unmounts. + +```jsx +const useMutationObserver = ( + ref, + callback, + options = { + attributes: true, + characterData: true, + childList: true, + subtree: true, + } +) => { + React.useEffect(() => { + if (ref.current) { + const observer = new MutationObserver(callback); + observer.observe(ref.current, options); + return () => observer.disconnect(); + } + }, [callback, options]); +}; +``` + +```jsx +const App = () => { + const mutationRef = React.useRef(); + const [mutationCount, setMutationCount] = React.useState(0); + const incrementMutationCount = () => { + return setMutationCount(mutationCount + 1); + }; + useMutationObserver(mutationRef, incrementMutationCount); + const [content, setContent] = React.useState('Hello world'); + + return ( + <> + +