Skip to content
Advertisement

How do you toggle between light and dark themes while current theme is being locally stored?

I am fairly new to react and I’m implementing some new features using Material-UI. I am trying to switch between light and dark themes while the current theme is being locally stored within the browser. I wish to locally store the current theme as the page refreshes. By default, my app loads in the light theme. Before toggling the switch, I verify to see that light theme is in local storage. As I toggle to dark theme, my app changes to its counterpart and the value within my local storage changes just as expected. But when I try to toggle the switch back to light theme, the theme doesn’t change, just my local storage value. I don’t know why.

If someone has a way of tweaking this code to address this problem or suggest a new idea, I greatly appreciate it.

Demo in CodeSandbox

CustomThemeContext.js

JavaScript

index.js

JavaScript

App.js

JavaScript

MyThemes.js

JavaScript

Advertisement

Answer

On your ThemeProvider component theme prop, clone the theme object you assign to it and it should work

JavaScript
Advertisement