I’m encountering an issue with theme switching in my React application. The application supports two themes, which I’ll refer to as Theme One and Theme Two. I’m using lazy loading to dynamically load the corresponding theme components based on the selected theme.
Each theme defines its own styling for a common button class. For example, in Theme One, the button has a red color, while in Theme Two, it has a brown color.
The problem arises when I switch themes using a button. Initially, when transitioning from Theme One to Theme Two, the button color updates correctly from red to brown. However, after switching back to Theme One, the button color fails to revert to red as expected. Subsequent theme switches also don’t reflect any changes in the button color.
Here’s a simplified version of my code structure:
// App.js
import React, { useState, Suspense } from 'react';
import ThemeContext from './ThemeContext';
import './App.css';
const ThemeOne = React.lazy(() => import('./ThemeOne'));
const ThemeTwo = React.lazy(() => import('./ThemeTwo'));
const App = () => {
const [theme, setTheme] = useState('one');
const handleChangeTheme = () => {
startTransition(() => {
if (_theme === 'Theme One') {
setTheme('Theme Two');
} else {
setTheme('Theme One');
}
});
};
return (
<ThemeContext.Provider value={{ theme, handleChangeTheme }}>
<Suspense fallback={<div>Loading...</div>}>
{theme === 'one' ? <ThemeOne /> : <ThemeTwo />}
</Suspense>
</ThemeContext.Provider>
);
};
export default App;
// ThemeOne.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
import './ThemeOne.css';
const ThemeOne = () => {
const { handleChangeTheme } = useContext(ThemeContext);
return (
<>
<button className="common-btn-one" onClick={handleChangeTheme}>
Theme One Button
</button>
</>
);
};
export default ThemeOne;
// ThemeTwo.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
import './ThemeTwo.css';
const ThemeTwo = () => {
const { handleChangeTheme } = useContext(ThemeContext);
return (
<>
<button className="common-btn-two" onClick={handleChangeTheme}>
Theme Two Button
</button>
</>
);
};
export default ThemeTwo;