useCssVar
Manipulate CSS variables
useCssVar reads and writes CSS custom properties (variables) on a target DOM element. It returns a tuple of the current variable value and a setter function. Optionally, it can observe changes via MutationObserver so the returned value stays in sync when external code modifies the variable.
When to Use
- Dynamically theming components by reading and updating CSS custom properties at runtime
- Building color pickers or style editors that manipulate CSS variables on specific elements
- Synchronizing React state with CSS variables for animations or transitions
Notes
- SSR-safe: Returns the provided default value and a no-op setter during server-side rendering. No DOM access occurs on the server.
- MutationObserver: Set
observe: truein options to automatically track external changes to the CSS variable via MutationObserver. - Target element: The hook requires a ref to a specific DOM element; changes are scoped to that element’s inline style.
Usage
Live Editor
function Demo() { const key = "--color"; const ref = useRef<HTMLDivElement>(null); const [color, setColor] = useCssVar(key, ref, ""); const style: any = { "--color": "#7fa998", "color": "var(--color)", }; const switchColor = () => { if (color === "#df8543") { setColor("#7fa998"); } else { setColor("#df8543"); } }; return ( <section> <div ref={ref} style={style}> Sample text, <>{color}</> </div> <button onClick={switchColor}>Change Color</button> </section> ); };
Result
API
useCssVar
Returns
readonly [string, (v: string) => void]: A tuple with the following elements:
- The current value of the css var.
- A function to update the value of the css var.
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| prop | prop, eg: --color | string (Required) | - |
| target | dom element | BasicTarget<T> (Required) | - |
| defaultValue | default value | string | undefined | - |
| options | options | UseCssVarOptions | undefined | - |
UseCssVarOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| observe | Use MutationObserver to monitor variable changes | boolean | false |
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;