useWindowSize
A React hook that tracks window dimensions and responsive breakpoints in real-time.
Overview
useWindowSize provides live updates of your browser's viewport dimensions along with convenience boolean flags for common responsive breakpoints. Perfect for building adaptive UIs that respond to resize events.
Demo
API Reference
function useWindowSize(): {
width: number,
height: number,
isMobile: boolean,
isTablet: boolean,
isDesktop: boolean
}Returns
| Name | Type | Description |
|---|---|---|
width | number | Current viewport width in pixels. |
height | number | Current viewport height in pixels. |
isMobile | boolean | true if width < 640px. |
isTablet | boolean | true if width is 640-1023px. |
isDesktop | boolean | true if width ≥ 1024px. |
Usage Examples
Responsive Component
import { useWindowSize } from 'react-hooks-ts'
function ResponsiveNav() {
const { isMobile } = useWindowSize()
return isMobile ? <MobileMenu /> : <DesktopNav />
}Conditional Rendering
import { useWindowSize } from 'react-hooks-ts'
function Dashboard() {
const { width, isDesktop } = useWindowSize()
return (
<div className={isDesktop ? 'grid-cols-3' : 'grid-cols-1'}>
{/* Content adapts to viewport */}
</div>
)
}Features
- ⚡ Debounced - Updates are throttled to prevent performance issues.
- 📱 Breakpoint Flags - Convenient booleans for mobile, tablet, and desktop.
- 🛡️ SSR Safe - Returns sensible defaults during server-side rendering.
- 🧹 Auto Cleanup - Event listeners are properly removed on unmount.