Menu

React Use Mobile Hook: SSR-Safe, No Hydration Mismatch
📰

React Use Mobile Hook: SSR-Safe, No Hydration Mismatch

DEV Community: nextjs·Serban Dan Rusu·16 days ago
#ccjGji4S
#devtonextjs#devto#dev#hook#server
Reading 0:00
15s threshold

TL;DR

A React use mobile hook returns false on the server because the server has no screen: it renders the HTML before any browser reports a width, and hydration has to repeat that guess. Switch visible layout with CSS breakpoints, which apply at first paint, and keep the hook for behavior after an interaction, such as opening a bottom sheet instead of a dialog. Build the hook on useSyncExternalStore with a server snapshot, so hydration matches and every later mount reads the real value on its first render.

Sooner or later, a Next.js app that has to work on phones grows a React use mobile hook: a useIsMobile() that returns true below 768px, copied from a starter or from shadcn/ui. It works in the browser, then surprises you three ways: it returns false on the server, a careless version throws a hydration error, and a phone can briefly see the desktop version of whatever the hook controls.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.