From fb6be97d7943b7743631fd2000f9da3cb565bacf Mon Sep 17 00:00:00 2001 From: unix Date: Sun, 24 May 2020 01:49:46 +0800 Subject: [PATCH] feat(utils): add hooks for dom observer --- components/utils/use-dom-observer.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 components/utils/use-dom-observer.ts diff --git a/components/utils/use-dom-observer.ts b/components/utils/use-dom-observer.ts new file mode 100644 index 0000000..258fb2a --- /dev/null +++ b/components/utils/use-dom-observer.ts @@ -0,0 +1,25 @@ +import { MutableRefObject, useEffect } from 'react' + +const useDOMObserver = ( + ref: MutableRefObject | undefined, + callback: MutationCallback = () => {}, +) => { + const config = { attributes: false, childList: true, subtree: true } + + useEffect(() => { + if (!ref || !ref.current) return + let unmount = false + const done: MutationCallback = (...params) => { + if (unmount) return + callback(...params) + } + const observer = new MutationObserver(done) + observer.observe(ref.current, config) + return () => { + unmount = true + observer.disconnect() + } + }, [ref]) +} + +export default useDOMObserver