How to Pass a React Variable to CSS
Use CSS custom properties from React, validate rendering behavior with React Scan, and know when a ref is better than state.
Today I learned a clean way to pass runtime values from React into CSS.
Why I write one learning per day
We do many things every day and absorb them passively. If we do not rewrite what we learned ourselves, we do not remember it well. Writing also forces us to use the correct names for concepts, which makes us better communicators.
Pass React values to CSS variables
Create a state value in React, then inject it as a CSS custom property on an element.
import { useState } from "react"
export function DistanceDemo() {
const [distance, setDistance] = useState(24)
return (
<div
style={{ "--distance": `${distance}px` } as React.CSSProperties}
className="moving-box"
>
<button onClick={() => setDistance((value) => value + 8)}>Move</button>
</div>
)
}
Then consume it in CSS with var(--distance) and calc().
.moving-box {
transform: translateX(calc(var(--distance) * 1));
transition: transform 160ms ease;
}
Is it performant?
Do not trust claims (including mine) without measuring.
You can add React Scan and test a minimal example:
<script
crossOrigin="anonymous"
src="//unpkg.com/react-scan/dist/auto.global.js"
></script>
Then interact with your component and inspect rerenders. In many cases, state updates are fine, but for values that do not need rendering, a ref is often better.
When to use useRef instead of state
If a value changes very often and does not need to trigger a React render, use useRef.
- Use state when UI must rerender.
- Use ref for mutable values used by effects, handlers, or imperative logic.
This keeps rendering cost under control while still giving you dynamic styling when needed.
