useWindowSize
Provides the current width and height of the browser window, updating on resize.
Code
1import { useState } from "react"
2import { useEventListener } from "./use-event-listener"
3import { useIsomorphicLayoutEffect } from "./use-isomorphic-layout-effect"
4
5interface WindowSize {
6 width: number
7 height: number
8}
9
10export function useWindowSize(): WindowSize {
11 const [windowSize, setWindowSize] = useState<WindowSize>({
12 width: 0,
13 height: 0,
14 })
15
16 const handleSize = () => {
17 setWindowSize({
18 width: window.innerWidth,
19 height: window.innerHeight,
20 })
21 }
22
23 useEventListener("resize", handleSize)
24
25 useIsomorphicLayoutEffect(() => {
26 handleSize()
27 }, [])
28
29 return windowSize
30}
Usage Example
import { useWindowSize } from "@/hooks/use-window-size"
import { Card, CardContent } from "@/components/ui/card"
export function WindowSizeExample() {
const { width, height } = useWindowSize()
return (
<Card className="p-4">
<CardContent className="p-0">
<p className="text-lg">Window Width: {width}px</p>
<p className="text-lg">Window Height: {height}px</p>
<p className="text-sm text-npui-muted-foreground mt-2">
(Resize your browser window to see the change)
</p>
</CardContent>
</Card>
)
}