Overview
TheuseDeviceType hook detects the user’s device type by monitoring the viewport width. It returns 'mobile', 'tablet', or 'desktop' and automatically updates when the window is resized.
This hook uses client-side detection based on viewport width breakpoints. It defaults to
'desktop' during server-side rendering to prevent hydration mismatches.Import
Usage
Basic Usage
Conditional Video Sources
Fromcomponents/organisms/video-background-section.tsx:7:
Conditional Rendering
Fromcomponents/organisms/shader-background.tsx:17:
Responsive Layout Switching
Fromapp/page.tsx:36:
Return Value
The current device type based on viewport width:
'mobile': Width ≤ 768px'tablet': Width > 768px and ≤ 1024px'desktop': Width > 1024px
'desktop' on initial render (before client-side measurement).Type Definition
Breakpoints
The hook uses the following viewport width breakpoints:| Device Type | Viewport Width |
|---|---|
| Mobile | ≤ 768px |
| Tablet | 769px - 1024px |
| Desktop | > 1024px |
Implementation Details
Resize Handling
The hook attaches a resize event listener to detect viewport changes:SSR Compatibility
The hook initializes state asnull and returns 'desktop' as the fallback:
Use Cases
- Responsive media: Load different video or image sources based on device
- Conditional features: Enable/disable features like WebGL effects on mobile
- Layout switching: Render completely different layouts for mobile vs desktop
- Performance optimization: Skip heavy animations or effects on mobile devices
- Navigation variants: Show different navigation components per device type
Performance Considerations
The hook re-renders the component on every window resize. For performance-critical scenarios, consider debouncing the resize handler or using CSS media queries instead.
Alternative: CSS Media Queries
For purely visual changes, CSS is more performant:- Different components rendered per device
- Device-specific logic or data fetching
- Programmatic access to device type
Real-World Usage
In the NJ Rajat Mahotsav application, this hook is used in:- Video backgrounds (
video-background-section.tsx:7) - Different video sources - Shader effects (
shader-background.tsx:17) - Disable on mobile for performance - Page layouts (
page.tsx:36) - Mobile vs desktop landing pages - Image marquees (
image-marquee.tsx:29) - Adjust animation speed - Navigation (
desktop-navigation.tsx:50) - Show/hide based on device - Forms (
registration/page.tsx:63) - Adjust form layouts
Related
- useIntersectionObserver - Another responsive hook for scroll-based detection
- Organisms - Video background section example usage
