UNPKG

@modern-kit/react

Version:
41 lines (38 loc) 1.25 kB
import { useRef, useState, useCallback, useEffect } from 'react'; function useComputedStyleObserver(key) { const ref = useRef(null); const observerRef = useRef(null); const [value, setValue] = useState(""); const setStyleValue = useCallback( (value2) => { if (!ref.current) return; const targetElement = ref.current; targetElement.style.setProperty(key, value2); setValue(value2); }, [key] ); const updateStyleValue = useCallback(() => { if (!ref.current) return; const targetElement = ref.current; const computedStyle = window.getComputedStyle(targetElement); const value2 = computedStyle.getPropertyValue(key).trim(); setValue(value2); }, [key]); useEffect(() => { if (!ref.current) return; const element = ref.current; updateStyleValue(); observerRef.current = new MutationObserver(updateStyleValue); observerRef.current.observe(element, { attributeFilter: ["style", "class"] // style, class 속성 변경을 관찰 }); return () => { observerRef.current?.disconnect(); }; }, [updateStyleValue]); return { ref, value, setValue: setStyleValue }; } export { useComputedStyleObserver }; //# sourceMappingURL=index.mjs.map