Overview
TheuseIsMobile hook provides a reactive boolean value that indicates whether the current viewport width is below the mobile breakpoint (768px). It listens to window resize events and updates automatically.
Usage
Signature
Return value
Returns
true if the viewport width is less than 768px, false otherwise. Initially returns false during server-side rendering or before the first client-side measurement.Breakpoint
The hook uses a fixed breakpoint constant:Behavior
Initial state
The hook returnsfalse initially (via !!undefined) to handle server-side rendering and prevent hydration mismatches.
Reactive updates
The hook:- Creates a media query listener for
(max-width: 767px) - Updates the state when the viewport crosses the breakpoint
- Checks
window.innerWidthdirectly for precise measurements - Cleans up the event listener on unmount
Implementation details
The hook uses both
matchMedia for efficient change detection and window.innerWidth for accurate width measurement.Common patterns
Conditional rendering
Conditional styling
Feature toggling
This hook is client-side only and will always return
false during SSR to prevent hydration errors.Source
See the full implementation inhooks/use-mobile.ts:5