material-ui icon indicating copy to clipboard operation
material-ui copied to clipboard

[system] useColorScheme should return null during hydration

Open oliviertassinari opened this issue 10 months ago • 4 comments

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: -

oliviertassinari avatar Apr 16 '24 00:04 oliviertassinari

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

yamahmed avatar Apr 23 '24 18:04 yamahmed

Capture d’écran 2024-04-23 193500

yamahmed avatar Apr 23 '24 18:04 yamahmed

Capture d’écran 2024-04-23 193542

yamahmed avatar Apr 23 '24 18:04 yamahmed

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.

yamahmed avatar Apr 23 '24 18:04 yamahmed

This is fixed by #42839

siriwatknp avatar Aug 26 '24 06:08 siriwatknp