material-ui
material-ui copied to clipboard
[system] useColorScheme should return null during hydration
Steps to reproduce
No response
Current behavior
useColorScheme()
returns a default value during hydration leading to confusion: it's not accurate and prevents combinatory logic like below.
Expected behavior
I would expect it to return null
, see:
https://github.com/mui/material-ui/blob/418fb02c5a37c518ca9bf954a0c1eacfbb69d53d/docs/src/components/header/ThemeModeToggle.tsx#L37-L46
for a use case.
Context
I saw this in https://github.com/mui/material-ui/pull/41223.
Your environment
npx @mui/envinfo
Don't forget to mention which browser you used.
Output from `npx @mui/envinfo` goes here.
Search keywords: -
Hey Olivier, i suggest we create a custom hook that provides more control over the initialization process. i'll provide an example of how to do it
In this custom hook 'useAccurateColorScheme', we use the useState and useEffect hooks to manage the state of the accurate color scheme. The useEffect hook runs after the component mounts and fetches the accurate color scheme (e.g., from local storage) and updates the state accordingly.
Then, in your component, you can use useAccurateColorScheme to retrieve the accurate color scheme and perform combinatory logic based on it. This ensures that the color scheme used in your component reflects the accurate value after hydration, preventing confusion caused by inaccurate default values.
This is fixed by #42839