Skip to content
Advertisement

Material-ui style getting overwritten when switching light/dark theme using useMediaQuery hook

I was using next.js and material-ui, and changes theme based on user preference. But it seems when switched to light mode, the Styles (using JSS) I set will get overwritten, It only happens when using light mode I even tried to reverse the two theme, but it doesn’t work. After a lot of trying I found when change the system/browser to use the theme different from the one set in the useMediaQuery() hook, the problem will happen. const isInDarkMode = useMediaQuery("(prefers-color-scheme: dark)"); (for instance when set prefers-color-scheme to dark, the light theme will cause Styles to be overwritten.) But I still do not know why this occoured and how to avoid.

Edit: After manually set isInDarkMode = false , The style got overwritten regardless of mode.. so probably useMediaQuery did not cause the problem but actually kinda solve the problem..?

Edit After I tried to deploy this app to vercel, Home page truned fully normal under all color modes, some pages generated by getStaticPaths() still has the problem.

This is tested both on Safari on iOS and Chrome on Windows, and the problem all occours.

Code I used to set Theme (I set it in _app.js):

JavaScript

(I have tried without useMemo, but did not solve the problem.)

JavaScript

(One example for the Style, The problem will cause all styles to be overwritten include maxWidth, BackgroundColor and border/borderRadius)

Advertisement

Answer

Problem solved! It seems like it is caused by not having the Server Side injected CSS removed. I followed the tutorial Here

For reference these are my _document.js

JavaScript

and _app.js

JavaScript

(I changed to create theme in a different file, but it should be optional)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement