Material-ui: [useMediaQuery] always returns false first at page-load

Created on 15 May 2020  路  3Comments  路  Source: mui-org/material-ui

At pageload, useMediaQuery will return false-negative if it was actually true, instantly forcing a re-render and correctly returning true.

  • [x] The issue is present in the latest release.
  • [x] I have searched the issues of this repository and believe that this is not a duplicate.

Current Behavior 馃槸

There are two ways to formulate it:

  • At pageload, useMediaQuery returns false first. Then, if they actually were true from the very beggining, they will force instant re-render, returning true.
  • At pageload, useMediaQuery will return false-negative if it was actually true, instantly forcing a re-render correctly returning true afterwards.

That leads to potential double-renders at page-load, impacting performance.

Expected Behavior 馃

useMediaQuery to return correct value with first time.

Steps to Reproduce 馃暪

https://codesandbox.io/s/lively-sky-gl983

Context 馃敠

I have a wrapper component that renders either A or B subcomponent based on a media querry, where both A and B are both rather heavy. With this problem, I can't ensure that I will render the right one first time, without wasting time rendering the other.

Your Environment 馃寧

See versions on https://codesandbox.io

useMediaQuery question

Most helpful comment

@Akuukis Checkout the noSsr option.

All 3 comments

@Akuukis Checkout the noSsr option.

Thanks, it works with noSsr. But it didn't behave like described:

[..] 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 [..]

Here I demonstrate that it may render once or twice, depending on the query and situation. Do I miss something, or docs should be updated?

@Akuukis Don't forget that StrictMode might be in the equation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mattmiddlesworth picture mattmiddlesworth  路  3Comments

FranBran picture FranBran  路  3Comments

zabojad picture zabojad  路  3Comments

ghost picture ghost  路  3Comments

ryanflorence picture ryanflorence  路  3Comments