[useMediaQuery] always returns false at the first call
See original GitHub issueDuplicate of #21048 - [useMediaQuery] always returns false first at page-load
- The issue is present in the latest release.
- I have searched the issues of this repository and believe that this is not a duplicate.
Current Behavior 😯
Well, the current behavior is clearly documented
options.noSsr (Boolean [optional]): Defaults to false. In order to perform the server-side rendering reconciliation, it needs to render twice. A first time with nothing and a second time with the children. This double pass rendering cycle comes with a drawback. It’s slower. You can set this flag to true if you are not doing server-side rendering.
However the current behavior is incorrect, and working NOT as documented
Just for context - here is useMediaQuery
source - https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/useMediaQuery/useMediaQuery.js#L44
const [match, setMatch] = React.useState(() => {
if (noSsr && supportMatchMedia) {
// unless noSsr is set, this line would be NEVER called
return matchMedia(query).matches;
}
if (ssrMatchMedia) {
return ssrMatchMedia(query).matches;
}
return defaultMatches;
});
From this code it’s clear that without noSsr set the match
would be always defaultMatches
at the first hook call.
While the intention was to keep it default (or ssrMatchMedia) only during hydrate. As a result even CSR only application sufferes from double rendering, which never ends while application is working.
Expected Behavior 🤔
Expected behaviour - useMedia
should set correct state just after application start.
const [match, setMatch] = React.useState(() => {
if ( (noSsr || pastHydration) && supportMatchMedia) {
return matchMedia(query).matches;
}
...
});
However there is a problem of tracking that event, especially with partial hydration in mind, when such event could occur more that once. (not sure MUI supports it)
Technically speaking no change is required to useMediaQuery
, but another functionality to provide correct value for noSsr
is needed.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:19
- Comments:23 (10 by maintainers)
Top GitHub Comments
Hi there! I’m encountering this behavior. I’m not using SSR so I don’t really understand how it influences this, but I’m having
useMediaQuery
return false in the initial call which results in a nasty flash of CSS. A result oftrue
means mobile, so the page is loading initially with the desktop styles (false
), then it instantly switches to the mobile styles). Am I doing something wrong, should I be setting some kind of parameter? Thanks!Can anyone please confirm if this situation is happening again?