日本語情報が見つからなかったため(※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
参考
Arguments
- 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.
- 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.