use-current-color-value.tsx

use the current css color of a passed ref or the document

import type React from "react";
import { useEffect, useState } from "react";

export function useCurrentColorValue(ref?: React.RefObject<HTMLElement>) {
  const [color, setColor] = useState<string | null>(null);

  useEffect(() => {
    const updateColor = () => {
      if (ref?.current) {
        setColor(getComputedStyle(ref.current).color);
      } else {
        // use document color
        setColor(getComputedStyle(window.document.documentElement).color);
      }
    };

    const observer = new MutationObserver(() => {
      updateColor();
    });

    // observe the root element for changes
    observer.observe(window.document.documentElement, {
      attributes: true,
      attributeFilter: ["class", "style"],
    });

    if (ref?.current) {
      // observe the container element for changes
      observer.observe(ref.current, {
        attributes: true,
        attributeFilter: ["class", "style"],
      });
    }

    updateColor();

    return () => observer.disconnect();
  }, [ref]);

  return color;
}