11import type { RefObject } from 'react' ;
22
3- import { useState } from 'react' ;
3+ import { useEffect , useState } from 'react' ;
44
55import { getElement } from '@/utils/helpers' ;
66
7- import { useMount } from '../useMount/useMount' ;
8- import { useMutationObserver } from '../useMutationObserver/useMutationObserver' ;
7+ import { useRefState } from '../useRefState/useRefState' ;
98
109/** The css variable target element type */
1110export type UseCssVarTarget =
@@ -43,7 +42,7 @@ export interface UseCssVar {
4342 * @returns {UseCssVarReturn } The object containing the value of the CSS variable
4443 *
4544 * @example
46- * const { value, set } = useCssVar('color', 'red');
45+ * const { ref, value, set } = useCssVar('color', 'red');
4746 *
4847 * @overload
4948 * @template Target The target element
@@ -63,9 +62,11 @@ export const useCssVar = ((...params: any[]) => {
6362 const initialValue = ( target ? params [ 2 ] : params [ 1 ] ) as string | undefined ;
6463
6564 const [ value , setValue ] = useState ( initialValue ?? '' ) ;
65+ const internalRef = useRefState < Element > ( window . document . documentElement ) ;
6666
6767 const set = ( value : string ) => {
68- const element = getElement ( target ?? window ?. document ?. documentElement ) as HTMLElement ;
68+ const element = ( target ? getElement ( target ) : internalRef . current ) as HTMLElement ;
69+ if ( ! element ) return ;
6970
7071 if ( element . style ) {
7172 if ( ! value ) {
@@ -79,25 +80,33 @@ export const useCssVar = ((...params: any[]) => {
7980 }
8081 } ;
8182
82- const updateCssVar = ( ) => {
83- const element = getElement ( target ?? window ?. document ?. documentElement ) as HTMLElement ;
83+ useEffect ( ( ) => {
84+ if ( initialValue ) set ( initialValue ) ;
85+ } , [ ] ) ;
86+
87+ useEffect ( ( ) => {
88+ if ( ! target && ! internalRef ) return ;
89+
90+ const element = ( target ? getElement ( target ) : internalRef . current ) as Element ;
8491 if ( ! element ) return ;
8592
86- const value = window
87- . getComputedStyle ( element as Element )
88- . getPropertyValue ( key )
89- ?. trim ( ) ;
93+ const updateCssVar = ( ) => {
94+ const value = window
95+ . getComputedStyle ( element as Element )
96+ . getPropertyValue ( key )
97+ ?. trim ( ) ;
9098
91- setValue ( value ?? initialValue ) ;
92- } ;
99+ setValue ( value ?? initialValue ) ;
100+ } ;
93101
94- useMount ( ( ) => {
95- if ( initialValue ) set ( initialValue ) ;
96- } ) ;
102+ const observer = new MutationObserver ( updateCssVar ) ;
103+
104+ observer . observe ( element , { attributeFilter : [ 'style' , 'class' ] } ) ;
97105
98- useMutationObserver ( window , updateCssVar , {
99- attributeFilter : [ 'style' , 'class' ]
100- } ) ;
106+ return ( ) => {
107+ observer . disconnect ( ) ;
108+ } ;
109+ } , [ target , internalRef . current ] ) ;
101110
102111 return {
103112 value,
0 commit comments