wkkkis-hooks

use-window-size (use-window-size)

Tracks the current window's dimensions.

v0.1.0

Usage

import { use-window-size } from "@/hooks"
1"use client"; 2 3import { 4 Card, 5 CardContent, 6 CardDescription, 7 CardFooter, 8 CardHeader, 9 CardTitle, 10} from "@/components/ui/card"; 11 12import { useWindowSize } from "@/components/hooks/use-window-size"; 13 14export function UseWindowSizeDemo() { 15 const { width, height } = useWindowSize({ 16 initialWidth: 1024, 17 initialHeight: 768, 18 }); 19 20 return ( 21 <Card className="relative max-w-sm w-full"> 22 <CardHeader> 23 <CardTitle>useWindowSize</CardTitle> 24 <CardDescription> 25 This component uses the <code>useWindowSize</code> hook to get the 26 current window size. 27 </CardDescription> 28 </CardHeader> 29 <CardContent> 30 <p>Width: {width}</p> 31 <p>Height: {height}</p> 32 </CardContent> 33 <CardFooter> 34 <p className="text-sm text-muted-foreground"> 35 Resize the window to see the values changing. 36 </p> 37 </CardFooter> 38 </Card> 39 ); 40} 41

Install

npx wkkkis-hooks add use-window-size

Options

NameTypeDefaultDescription
initialWidth?numberundefinedThe initial width of the window. (optional)
initialHeight?numberundefinedThe initial height of the window. (optional)
onChange?(width: number, height: number) => voidundefinedA callback function that is called when the window's dimensions change. (optional)

SSR & Initial Values

  • The hook detects if it is running in a browser. If not, it uses 0 for initial width/height unless initialWidth / initialHeight are provided.
  • On the client, the initial values default to the current window size unless overridden by props.

onChange Callback

  • The onChange callback is called every time the window is resized, after the state is updated.
  • The callback receives the new width and height as arguments.

Immediate Update on Mount

  • The hook immediately updates the state and calls onChange on mount to ensure the values are up-to-date with the actual window size.

Cleanup

  • The resize event listener is removed automatically when the component unmounts.

Caveats & Best Practices

  • The hook is intended for use in the browser; on the server, it will always return the initial values.
  • If you need to debounce or throttle resize events, wrap the hook or the callback accordingly.
  • The hook returns an object with width and height .

Files in this hook

SourceDestination
files/use-window-size.tssrc/hooks/use-window-size.ts