useIsMobile
TheuseIsMobile hook detects whether the current device is mobile by checking if the viewport width is less than 768px. It listens to window resize events and updates automatically.
Installation
Import
Usage
Returns
boolean
A boolean value indicating whether the viewport width is less than 768px. Returns
false during server-side rendering and updates after mounting on the client.Type Definition
Breakpoint
The hook uses a mobile breakpoint of 768px:isMobile = truewhen viewport width is < 768pxisMobile = falsewhen viewport width is >= 768px
Examples
Responsive Navigation
Conditional Component Rendering
Different Layouts
Touch vs Click Events
Responsive Image Loading
Modal Behavior
Responsive Table
Common Patterns
Combining with CSS Classes
Conditional Hook Calls
Performance Optimization
Notes
- The hook returns
falseduring server-side rendering - The initial state is
undefined, which is coerced tofalseby the!!operator - The hook automatically updates when the window is resized
- Event listeners are properly cleaned up when the component unmounts
- The 768px breakpoint is commonly used as the mobile/tablet boundary
- For more complex responsive logic, consider using
useMediaQueryhook instead - The hook uses
window.matchMediafor efficient media query matching - This hook is ideal for simple mobile/desktop detection; for more granular control, use custom media queries