useComputedStyleObserver
A React hook that observes and manages a specific computed style value of a target element in real time.
- Uses MutationObserver to invoke a callback whenever the element's style attribute changes.
- Reflects changes made directly via CSSStyleDeclaration: setProperty in real time.
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
| Name | Type | Description |
|---|---|---|
key | string | The CSS style property key to observe (e.g. 'width', 'color', 'font-size') |
Returns
| Name | Type | Description |
|---|---|---|
ref | React.RefObject<T | null> | A ref object to attach to the target element to observe. |
value | string | The current observed computed style value. |
setValue | (value: string) => void | A function to directly update the computed style value. |
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>Current width: {`${value}`}</p>
<button onClick={() => setValue('100px')}>Set width to 100px (setValue)</button>
<button onClick={() => setValue('300px')}>Set width to 300px (setValue)</button>
<br />
<button onClick={() => ref.current?.style.setProperty('width', '100px')}>Set width to 100px (setProperty)</button>
<button onClick={() => ref.current?.style.setProperty('width', '300px')}>Set width to 300px (setProperty)</button>
</div>
</>
);
};
Example
Current width: