Skip to content

[useMediaQuery] always returns false at the first call #21142

@theKashey

Description

@theKashey

Duplicate 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueGreat for first contributions. Enable to learn the contribution process.hook: useMediaQuerytype: new featureExpand the scope of the product to solve a new problem.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions