API Reference
useCustomCSSProp

useCustomCSSProp

This hook allows you to monitor the current value of a CSS custom property, enabling you to reflect its current value within your React component.

Usage

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useCustomCSSProp into your component.

import { useCustomCSSProp } from '@ridgehkr/useful'

Example 1: Using a prop set at the document root

useCustomCSSProp tracks the value of a CSS custom prop for you and returns a string reflecting its current value. By default, it will look for the custom property on the documentElement (i.e. the <html> element).

In your CSS:

CSS
:root {
  --theme-color: #ffcc00;
}

In your React component:

MyComponent.jsx
import { useCustomCSSProp } from '@ridgehkr/useful'
 
export function MyComponent() {
  const themeColor = useCustomCSSProp('--theme-color')
 
  // "Current theme color: #ffcc00"
  return <div>Current theme color: {themeColor}</div>
}

Example 2: Using a CSS property set on a non-root element

You can also specify a different root element to monitor for the custom property by passing in a ref as a second parameter.

In your CSS:

CSS
.button {
  --radius: 0.5em;
}

In your React component:

Button.jsx
import { useCustomCSSProp } from '@ridgehkr/useful'
 
function Button() {
  const buttonRef = useRef(null)
  const buttonRadius = useCustomCSSProp('--radius', buttonRef)
 
  return (
    <button
      type='button'
      className='button'
      ref={buttonRef}
      style={{ borderRadius: buttonRadius }}
    >
      Rounded Button
    </button>
  )
}

API Reference

Parameters

useCustomCSSProp accepts two parameters:

PropertyTypeRequiredDescription
propertystringyesThe name of the CSS custom property you want to track.
rootReact.RefObject<HTMLElement>no (defaults to document root)A reference to the element where the CSS custom property should be monitored.

Return Value

useCustomCSSProp returns the current value of the specified CSS custom property as a string. If the custom property does not exist or is not set, it returns an empty string.

TypeDescription
stringThe value of the custom prop being tracked

How it Works

This hook retrieves the current value of the CSS custom property and sets up a MutationObserver (opens in a new tab) to efficiently monitor changes to the custom property. When a change is detected, the hook updates its state with the new value.