Last active
November 5, 2023 09:50
-
-
Save azaek/ba4038fc34338ed3954854a54a853ec4 to your computer and use it in GitHub Desktop.
Mutation Observer to get specific element addition or removal callback on dom manipulation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from "react"; | |
interface Callbacks { | |
onVisible?: () => void; | |
onHidden?: () => void; | |
} | |
const useMutationObserver = ( | |
elementId: string, | |
callbacks: Callbacks = { | |
onVisible: () => { }, | |
onHidden: () => { } | |
}) => { | |
let visibleRef = useRef(false); | |
const mutationObserver = new MutationObserver(function (_) { | |
let element = document.getElementById(elementId); | |
if (element) { | |
if (!visibleRef?.current) { | |
callbacks.onVisible?.(); | |
visibleRef.current = true; | |
} | |
} else { | |
if (visibleRef.current) { | |
callbacks.onHidden?.(); | |
visibleRef.current = false; | |
} | |
} | |
}); | |
useEffect(() => { | |
mutationObserver.observe(document.body, { subtree: false, childList: true }); | |
return () => { | |
mutationObserver.disconnect(); | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []) | |
return { | |
visibleRef | |
} | |
} | |
export default useMutationObserver; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment