DEV Community

Jason Clark
Jason Clark

Posted on

Chakra-UI + Next.js - Breaking React "Rules"

For the last 7 years doing React development, I've always been of the belief that in those times where you need to render different components based on responsiveness (i.e. media queries), you should always use a ternary based on the responsive breakpoint. In Chakra-UI, this is greatly simplified with the useBreakpointValue hook that's provided that returns a value based on what breakpoint the viewport lies within.

For instance:
const isMobile = useBreakpointValue({ base: true, md: false });

This is great for traditional client side rendered (CSR) pages, but things are a little different for SSG/SSR pages because it depends on Javascript in order to help evaluate the current viewport.

For the last few months, we've seen an issue where our statically generated pages at chatbooks.com would show a brief FOMC (Flash of Mobile Content) before rendering the desktop version. This was especially distracting as we use a considerably different Navbar between mobile and desktop (logo moves, hamburger menu vs supermenu, etc) and so the flash is QUITE noticeable.

Thankfully, looking at other people's code (specifically, thirdweb.com, THANKS) helped me see the error of my ways. Because these pages are pre-rendered and the HTML is stored, it requires a bit of a mind shift to recognize that adding a little extra HTML isn't a huge deal and will allow for a MUCH better experience, because we now render both mobile and desktop components, but use the display (with breakpoints) to manage display, which means there is no more FOMC.

Example:
<Box display={{ base: 'none', md: 'block|flex|grid'}}>...</Box>

Now, obviously, the best solution would be to keep the layouts as similar as possible, but that definitely doesn't always work, and this way, the page renders properly, since CSS loads faster than JS.

Top comments (0)