본문으로 건너뛰기

useComputedStyleObserver

관찰할 타겟 요소의 특정 computed style 값을 실시간으로 관찰하고 관리하는 React 훅

  • MutationObserver 를 사용하여 요소의 스타일 속성이 변경될 때 콜백을 호출합니다.
  • CSSStyleDeclaration: setProperty 를 사용하여 요소의 스타일 속성을 직접 변경하더라도 이를 실시간으로 반영합니다.

Code

🔗 실제 구현 코드 확인


Interface

typescript
interface UseComputedStyleObserverReturnType<T extends HTMLElement> {
ref: React.RefObject<T | null>;
value: string;
setValue: (value: string) => void;
}
typescript
function useComputedStyleObserver<T extends HTMLElement>(
key: string
): UseComputedStyleObserverReturnType<T>;

Parameters

NameTypeDescription
keystring관찰할 CSS 스타일 속성 키 (예: 'width', 'color', 'font-size')

Returns

NameTypeDescription
refReact.RefObject<T | null>관찰할 타겟 요소에 연결할 ref 객체입니다.
valuestring현재 관찰 중인 computed style 값입니다.
setValue(value: string) => voidcomputed style 값을 직접 변경하는 함수입니다.

Usage

typescript
import { useComputedStyleObserver } from '@modern-kit/react';

const Example = () => {
const { ref, value, setValue } =
useComputedStyleObserver<HTMLDivElement>('color');

return (
<>
<div ref={ref} style={{ width: '100px', height: '100px', backgroundColor: 'skyblue' }} />
<div>
<p>현재 너비: {`${value}`}</p>
<button onClick={() => setValue('100px')}>너비 100px로 변경(setValue)</button>
<button onClick={() => setValue('300px')}>너비 300px로 변경(setValue)</button>

<br />

<button onClick={() => ref.current?.style.setProperty('width', '100px')}>너비 100px로 변경(setProperty)</button>
<button onClick={() => ref.current?.style.setProperty('width', '300px')}>너비 300px로 변경(setProperty)</button>
</div>
</>
);
};

Example

현재 너비: