DEV Community

Jason Clark
Jason Clark

Posted on

6 2

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay