> ## Documentation Index
> Fetch the complete documentation index at: https://docs.uniwind.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# useCSSVariable

> Access CSS variable values in JavaScript with automatic theme updates

<Badge>Available in Uniwind 1.0.5+</Badge>

## Overview

The `useCSSVariable` hook allows you to retrieve one or more 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.

<Warning>
  This hook should be used sparingly. For most styling use cases, prefer using the `className` prop with Tailwind utilities.
</Warning>

## When to Use This Hook

Use `useCSSVariable` 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

<Tip>
  **Prefer these alternatives when possible:**

  * For styling components: Use the `className` prop directly
  * For multiple style properties: Use [`useResolveClassNames`](/api/use-resolve-class-names)
  * For third-party components: Wrap them with [`withUniwind`](/api/with-uniwind)
</Tip>

## Usage

### Basic Example

```tsx theme={null}
import { useCSSVariable } from 'uniwind'
import { View, Text } from 'react-native'

export const MyComponent = () => {
  const primaryColor = useCSSVariable('--color-primary')
  const spacing = useCSSVariable('--spacing-4')

  return (
    <View className="p-4">
      <Text>Primary color: {primaryColor}</Text>
      <Text>Spacing: {spacing}</Text>
    </View>
  )
}
```

### Multiple Variables at Once

You can also retrieve multiple CSS variables at once by passing an array:

```tsx theme={null}
import { useCSSVariable } from 'uniwind'
import { View, Text } from 'react-native'

export const MyComponent = () => {
  const [primaryColor, spacing, backgroundColor] = useCSSVariable([
    '--color-primary',
    '--spacing-4',
    '--color-background'
  ])

  return (
    <View className="p-4" style={{ backgroundColor }}>
      <Text style={{ color: primaryColor }}>
        Primary color: {primaryColor}
      </Text>
      <Text>Spacing: {spacing}</Text>
    </View>
  )
}
```

<Tip>
  Using the array syntax is more efficient than calling `useCSSVariable` multiple times, as it only subscribes to theme changes once.
</Tip>

### With Chart Libraries

```tsx theme={null}
import { useCSSVariable } from 'uniwind'
import { LineChart } from 'react-native-chart-kit'

export const ThemedChart = () => {
  const [primaryColor, backgroundColor, textColor] = useCSSVariable([
    '--color-primary',
    '--color-background',
    '--color-foreground'
  ])

  return (
    <LineChart
      data={chartData}
      width={300}
      height={200}
      chartConfig={{
        backgroundColor: backgroundColor,
        backgroundGradientFrom: backgroundColor,
        backgroundGradientTo: backgroundColor,
        color: () => primaryColor,
        labelColor: () => textColor,
      }}
    />
  )
}
```

### Accessing Custom Theme Variables

```tsx theme={null}
import { useCSSVariable } from 'uniwind'
import MapView, { Marker } from 'react-native-maps'

export const ThemedMap = () => {
  const markerColor = useCSSVariable('--color-accent')

  return (
    <MapView>
      <Marker
        coordinate={{ latitude: 37.78, longitude: -122.4 }}
        pinColor={markerColor}
      />
    </MapView>
  )
}
```

## 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's `className` props:

```tsx theme={null}
// Somewhere in your app
<View className="bg-primary" />
```

This makes `--color-primary` available to `useCSSVariable`:

```tsx theme={null}
const primaryColor = useCSSVariable('--color-primary') // ✅ Works
```

### 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 your `global.css`:

```css global.css theme={null}
@import 'tailwindcss';
@import 'uniwind';

@theme static {
  --color-al-teal-10: #eaeeee;
  --color-al-teal-25: #cad4d5;
  --color-al-teal-75: #607d81;
  --color-al-teal-100: #2b5257;

  --color-custom-teal-10: #eaeeee;
  --color-custom-teal-25: #cad4d5;
  --color-custom-teal-75: #607d81;
  --color-custom-teal-100: #2b5257;

  --chart-line-width: 2;
  --chart-dot-radius: 4;
}
```

Then access them anywhere:

```tsx theme={null}
const tealColor = useCSSVariable('--color-al-teal-75') // ✅ Works
const lineWidth = useCSSVariable('--chart-line-width') // ✅ Works
```

<Info>
  Variables defined in `@theme static` are always available, even if they're never used in any `className`.
</Info>

## Development Warnings

In development mode, Uniwind will warn you if you try to access a variable that hasn't been made available:

```tsx theme={null}
const unknownColor = useCSSVariable('--color-unknown')
// Console warning:
// "We couldn't find your variable --color-unknown. Make sure it's used
// at least once in your className, or define it in a static theme as
// described in the docs."
```

<Tip>
  If you see this warning, either use the variable in a `className` somewhere or add it to `@theme static` in your `global.css`.
</Tip>

## API Reference

### Arguments

<ParamField path="name" type="string | string[]" required>
  The name of the CSS variable(s) to retrieve, including the `--` prefix.

  * **Single variable**: Pass a string (e.g., `'--color-primary'`)
  * **Multiple variables**: Pass an array of strings (e.g., `['--color-primary', '--spacing-4']`)
</ParamField>

### Return Value

The return type depends on the input:

<ParamField path="single value" type="string | number | undefined">
  When passing a **single string**, returns the resolved value of the CSS variable:

  * **Web**: Always returns a `string` (e.g., `"16px"`, `"#ff0000"`)
  * **Native**: Returns `string` or `number` depending on the value type (e.g., `16`, `"#ff0000"`)
  * **Undefined**: If the variable cannot be found
</ParamField>

<ParamField path="array of values" type="Array<string | number | undefined>">
  When passing an **array of strings**, returns an array of resolved values in the same order:

  ```tsx theme={null}
  const [color, spacing, radius] = useCSSVariable([
    '--color-primary',   // Returns: "#3b82f6"
    '--spacing-4',       // Returns: 16 (on native) or "16px" (on web)
    '--radius-lg'        // Returns: 12 (on native) or "12px" (on web)
  ])
  ```
</ParamField>

## Platform Differences

<Accordion title="Web Platform" icon="globe">
  On web, `useCSSVariable` uses `getComputedStyle()` to retrieve values from the DOM. All values are returned as strings:

  ```tsx theme={null}
  // Single variable
  const color = useCSSVariable('--color-primary')
  // Web: "#3b82f6" (string)

  // Multiple variables
  const [color, spacing] = useCSSVariable(['--color-primary', '--spacing-4'])
  // Web: ["#3b82f6", "16px"] (strings)
  ```
</Accordion>

<Accordion title="Native Platform" icon="mobile">
  On React Native, `useCSSVariable` accesses the internal variable store. Numeric values are returned as numbers:

  ```tsx theme={null}
  // Single variable
  const spacing = useCSSVariable('--spacing-4')
  // Native: 16 (number)

  const color = useCSSVariable('--color-primary')
  // Native: "#3b82f6" (string)

  // Multiple variables
  const [color, spacing] = useCSSVariable(['--color-primary', '--spacing-4'])
  // Native: ["#3b82f6", 16] (mixed types)
  ```
</Accordion>

## Performance Considerations

<Info>
  The `useCSSVariable` hook is reactive and will automatically update when the theme changes, ensuring your values stay in sync with the active theme.
</Info>

Keep in mind:

* The hook subscribes to theme changes, so components will re-render when themes switch
* **Use array syntax for multiple variables**: When you need multiple CSS variables, pass an array instead of calling the hook multiple times. This creates only one subscription instead of multiple.
* For static values that don't need theme reactivity, consider storing them outside the component

**Example of efficient usage:**

```tsx theme={null}
// ✅ Good: Single subscription
const [color, spacing, radius] = useCSSVariable([
  '--color-primary',
  '--spacing-4',
  '--radius-lg'
])

// ❌ Less efficient: Multiple subscriptions
const color = useCSSVariable('--color-primary')
const spacing = useCSSVariable('--spacing-4')
const radius = useCSSVariable('--radius-lg')
```

## Related

<CardGroup cols={2}>
  <Card title="useResolveClassNames" icon="code" href="/api/use-resolve-class-names">
    Convert full className strings to style objects
  </Card>

  <Card title="Global CSS" icon="css" href="/theming/global-css">
    Learn how to define CSS variables in your theme
  </Card>

  <Card title="Theming Basics" icon="palette" href="/theming/basics">
    Understand how themes work in Uniwind
  </Card>

  <Card title="withUniwind" icon="layer-group" href="/api/with-uniwind">
    Wrap third-party components to add className support
  </Card>
</CardGroup>
