Overview
TheuseCSSVariable hook allows you to retrieve CSS variable values directly in JavaScript. Itโs particularly useful when you need to access theme colors, spacing values, or other design tokens programmatically for calculations, animations, or third-party library configurations.
When to Use This Hook
UseuseCSSVariable when you need to:
- Access theme colors for third-party libraries (e.g., chart libraries, map markers)
- Perform calculations with design tokens (e.g., dynamic positioning based on spacing values)
- Configure native modules that require color/size values
- Pass theme values to JavaScript animation libraries
- Access design tokens for runtime logic
Usage
Basic Example
With Chart Libraries
Accessing Custom Theme Variables
Making Variables Available
For the hook to resolve a CSS variable, the variable must be either:Option 1: Used in a className (Recommended)
Use the variable at least once anywhere in your appโsclassName props:
--color-primary available to useCSSVariable:
Option 2: Define in Static Theme
If you have CSS variables that are never used in classNames but need to be accessed in JavaScript, define them in a static theme block in yourglobal.css:
global.css
Variables defined in
@theme static are always available, even if theyโre never used in any className.Development Warnings
In development mode, Uniwind will warn you if you try to access a variable that hasnโt been made available:API Reference
Arguments
The name of the CSS variable to retrieve, including the
-- prefix (e.g., --color-primary, --spacing-4).Return Value
The resolved value of the CSS variable. The type depends on the platform:
- Web: Always returns a
string(e.g.,"16px","#ff0000") - Native: Returns
stringornumberdepending on the value type (e.g.,16,"#ff0000") - Undefined: If the variable cannot be found
Platform Differences
Web Platform
Web Platform
On web,
useCSSVariable uses getComputedStyle() to retrieve values from the DOM. All values are returned as strings:Native Platform
Native Platform
On React Native,
useCSSVariable accesses the internal variable store. Numeric values are returned as numbers:Performance Considerations
The
useCSSVariable hook is reactive and will automatically update when the theme changes, ensuring your values stay in sync with the active theme.- The hook subscribes to theme changes, so components will re-render when themes switch
- For static values that donโt need theme reactivity, consider storing them outside the component
- Accessing many variables in a single component is fine, but consider grouping related logic