Skip to content

Instantly share code, notes, and snippets.

@azaek
Last active November 5, 2023 09:50
Show Gist options
  • Save azaek/ba4038fc34338ed3954854a54a853ec4 to your computer and use it in GitHub Desktop.
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
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