In my React application, I'm facing a challenge with theme switching. There are two themes available: Theme One and Theme Two. To dynamically load theme components, lazy loading has been implemented based on the selected theme.
Each theme has its own styling for a common button class. In Theme One, the button appears blue, while in Theme Two, it is brown.
The issue arises when switching themes using a button. Initially, when moving from Theme One to Theme Two, the button color changes correctly from brown to blue. However, upon returning to Theme One, the button color fails to revert to brown as expected. Subsequent theme switches also do not update the button color accordingly.
For code reference, please visit: here
// App.js
import React, { createContext, useState, startTransition, useEffect } from "react";
// Lazy load themes
const ThemeOne = React.lazy(() => import("./themes/theme-one"));
const ThemeTwo = React.lazy(() => import("./themes/theme-two"));
export const MawbThemeContext = createContext({ _theme: "" });
const App = () => {
const [_theme, setTheme] = useState("themeOne");
const handleChangeTheme = () => {
startTransition(() => {
if (_theme === "themeOne") {
setTheme("themeTwo");
} else {
setTheme("themeOne");
}
});
};
let themeComponent;
if (_theme === "themeOne") {
themeComponent = <ThemeOne handleChangeTheme={handleChangeTheme} />;
} else if (_theme === "themeTwo") {
themeComponent = <ThemeTwo handleChangeTheme={handleChangeTheme} />;
} else {
themeComponent = <ThemeTwo handleChangeTheme={handleChangeTheme} />;
}
useEffect(() => {
startTransition(() => {
console.log("transition", _theme); // Ensure theme is changing correctly
});
}, [_theme]);
return (
<>
<MawbThemeContext.Provider value={{ _theme }}>
{themeComponent}
</MawbThemeContext.Provider>
</>
);
};
export default App;
I would appreciate any insights into why the theme updates are not being reflected correctly, especially when transitioning between themes multiple times.