LoginSignup
7
0

More than 3 years have passed since last update.

Material-UIのusemediaQueryの初期値が常にfalseになる事を回避する方法

Posted at

日本語情報が見つからなかったため(※1)備忘録として残しておきます。

※1: Material-UIの公式ドキュメントの日本語訳には存在するが翻訳が少しわかりにくい

状況

useMediaQuery()で横幅が992px以上であることを判定したいが、初回のuseMediaQueryの返り値がfalseのため2回レンダーされパフォーマンス的によろしくない。

const isWide = useMediaQuery('(min-width: 992px)')
console.log(isWide)

// console↓
// false
// true

対応策

この機能はサーバーサイドレンダリング(SSR)をする時には必要(あると便利・・・?)らしいのですが、SSRが必要ないアプリのためこの機能をオフにします。

const isWide = useMediaQuery('(min-width: 992px)', {noSsr: true})
console.log(isWide)

// console↓
// true

参考

useMediaQuery - Material-UI

Arguments
1. query (String | Function): A string representing the media query to handle or a callback function accepting the theme (in the context) that returns a string.
2. options (Object [optional]):
- options.defaultMatches (Boolean [optional]): As window.matchMedia() is unavailable on the server, we return a default matches during the first mount. The default value is false.
- options.matchMedia (Function [optional]) You can provide your own implementation of matchMedia. This can be used for handling an iframe content window.
- 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.
- options.ssrMatchMedia (Function [optional]) You can provide your own implementation of matchMedia in a server-side rendering context.

7
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
0