Improve media queries #15
-
There is no discussion tab activated for this repository, so I share my thoughts here. I found this repo (thank you so much!) when i stumbled over a problem when using the orientation property of the MaterialUI Stepper component. The goal was to display a horizontal Stepper when the display width is less than xl (1536px), otherwise a vertical Stepper. I got a very ugly layout shift when using a media query to evaluate the correct orientation by doing this: const matchesDownXl = useMediaQuery(theme.breakpoints.down('xl'))
const orientation = matchesDownXl ? 'horizontal' : 'vertical'; The solution for that problem was to add a hint that measures the window width: export const windowWidthHint = {
cookieName: 'CH-window-width',
getValueCode: 'window.screen.width',
// xl breakpoint: https://mui.com/material-ui/customization/breakpoints/
fallback: 1536,
transform: (value) => {
return parseInt(value, 10);
},
} as const satisfies ClientHint<number>; With that hint I was able to level up my media queries by using the const hints = useHints();
const matchesDownXl = useMediaQuery(theme.breakpoints.down('xl'), {
ssrMatchMedia: () => ({
matches: hints.windowWidth < theme.breakpoints.values.xl,
}),
}); Now the media query is evaluated correctly on the server and there are no more shifts anymore. :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This is fine, however you need to realize that any change in the value will trigger a reload of the browser when the user makes a document request. It's unobservable, but not entirely optimal, especially in a scenario like this where the chances the value is exactly the same every time are pretty low. So every user would likely refresh each time they come to the app. I can't tell you whether or not this is always good or always bad. Really depends on what trade-offs you're happy with. It's probably fine for many cases, but I would recommend using CSS for most problems like this instead of using a client hint for something that changes so frequently. |
Beta Was this translation helpful? Give feedback.
This is fine, however you need to realize that any change in the value will trigger a reload of the browser when the user makes a document request. It's unobservable, but not entirely optimal, especially in a scenario like this where the chances the value is exactly the same every time are pretty low. So every user would likely refresh each time they come to the app.
I can't tell you whether or not this is always good or always bad. Really depends on what trade-offs you're happy with. It's probably fine for many cases, but I would recommend using CSS for most problems like this instead of using a client hint for something that changes so frequently.