Skip to main content

useComputedStyleObserver

A React hook that observes and manages a specific computed style value of a target element in real time.


Code

🔗 View source 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
keystringThe CSS style property key to observe (e.g. 'width', 'color', 'font-size')

Returns

NameTypeDescription
refReact.RefObject<T | null>A ref object to attach to the target element to observe.
valuestringThe current observed computed style value.
setValue(value: string) => voidA 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: