useMutationObserver
Watch for changes being made to the DOM tree. MutationObserver MDN
Usage
Live Editor
function Demo() { const options = { attributes: true }; const [width, setWidth] = useState(200); const [count, setCount] = useState(0); const ref = useRef<HTMLDivElement>(null); const stop = useMutationObserver( (mutationsList) => { mutationsList.forEach(() => setCount(c => c + 1)); }, ref, options, ); useEffect(() => { setWidth(300); }, []); return ( <div> <div ref={ref} style={{ width, padding: 12, border: "1px solid #000", marginBottom: 8, }} > current width:{width} </div> <button onClick={() => setWidth(w => w + 10)}>widening</button> <button onClick={() => stop()}>stop observe</button> <p>Mutation count {count}</p> </div> ); };
Result
Loading...
API
UseMutationObserver
Returns
() => void
: stop listenering function
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
callback | callback | MutationCallback (Required) | - |
target | dom对象 | BasicTarget (Required) | - |
options | options passed to MutationObserver | MutationObserverInit | undefined | - |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;