A custom hook for detecting mobile screen sizes using CSS media queries.
src/hooks/use-mobile.ts
function useIsMobile(): booleanNone
boolean:trueif the screen width is below the mobile breakpoint (768px),falseotherwise
import { useIsMobile } from '@/hooks/use-mobile';
function ResponsiveComponent() {
const isMobile = useIsMobile();
return (
<div>
{isMobile ? (
<MobileLayout />
) : (
<DesktopLayout />
)}
</div>
);
}- Responsive breakpoint: Uses 768px as the mobile breakpoint
- Real-time updates: Automatically updates when window is resized
- SSR compatible: Returns
falseinitially to prevent hydration mismatches - Performance optimized: Uses
matchMediafor efficient media query listening
- Breakpoint:
MOBILE_BREAKPOINT = 768pixels - Media Query:
(max-width: 767px) - Event Listener: Automatically adds/removes resize event listeners
- Initial State: Starts with
undefined, then updates to actual value on mount
- Conditional rendering for mobile vs desktop layouts
- Responsive navigation menus
- Touch vs mouse interaction handling
- Mobile-specific features
- Responsive image loading
- Conditional component loading
- The hook returns
falseduring SSR to prevent hydration issues - The breakpoint matches common CSS framework conventions (Bootstrap, Tailwind)
- Uses
matchMediafor better performance than window resize events - Properly cleans up event listeners on unmount
- Modern browsers with
matchMediasupport - Gracefully degrades in older browsers