I have created a simple React project where I have inserted a Material UI switch in the drawer of my app that toggles the theme of the app from dark to light. The problem is sometimes when I load the app and click the switch, it doesn't respond the first few times. And when I keep clicking, it then changes the theme but the behavior is flipped: the way I made the switch is that the switch is checked/on when it is dark mode and off when it is light, but now, after not responding for the first few times, it changes the behavior and it is on when it is light mode and vice versa.
The way I am toggling the switch is this:
states that I used:
const [isDark, setDarkMode] = React.useState(true);
const [theme, setTheme] = React.useState(darkTheme);
toggleTheme function:
const toggleTheme = () => {
setDarkMode((prev) => !prev);
setTheme(isDark ? darkTheme : lightTheme);
};
and here is my switch:
<Switch edge="start" checked={isDark} onChange={toggleTheme} />
EDIT: And this issue still persists if i do this instead:
setTheme((prev) => prev === darkTheme? lightTheme: darkTheme);
Result: (behavior is still flipped)
Code:
My CodeSandbox link: https://codesandbox.io/s/testing-karmapact-app-bghgp?file=/App.js