CSS Custom Properties implementation guide in React on State Change
I've tried everything I can think of but I've been banging my head against this for hours... I need help solving I'm deploying to production and I'm working on a project and hit a roadblock. I'm working with an scenario where CSS custom properties (variables) are not updating dynamically when the state changes in my React component. I have implemented a theme switcher that should toggle between light and dark modes by changing the CSS variables. However, the styles do not reflect the new values after the state update. Hereβs a simplified version of my component: ```javascript import React, { useState } from 'react'; const ThemeSwitcher = () => { const [isDarkMode, setIsDarkMode] = useState(false); const toggleTheme = () => { setIsDarkMode(!isDarkMode); document.documentElement.style.setProperty('--bg-color', isDarkMode ? '#fff' : '#333'); document.documentElement.style.setProperty('--text-color', isDarkMode ? '#000' : '#fff'); }; return ( <div style={{ backgroundColor: 'var(--bg-color)', color: 'var(--text-color)' }}> <h1>Hello, World!</h1> <button onClick={toggleTheme}>Toggle Theme</button> </div> ); }; export default ThemeSwitcher; ``` In the above code, I expected the background and text colors to change when I toggle the theme. However, when I click the button, the colors do not change as expected, and I get the following behavior in the console: ``` Warning: need to perform a React state update on an unmounted component. ``` I verified that the `toggleTheme` function is being called, but the CSS variables do not seem to apply until a full page reload. I tried using the `useEffect` hook to set the properties based on the `isDarkMode` state, but that didnβt work either. What am I missing here? Is there a better way to manage CSS custom properties in a React component like this? This is part of a larger API I'm building. Thanks in advance! This is part of a larger desktop app I'm building. Thanks for taking the time to read this! I'm working in a Windows 11 environment. Any help would be greatly appreciated! Is this even possible? I'm working on a REST API that needs to handle this. I'd be grateful for any help.