Hooks/UI & DOM/useWindowSize

useWindowSize

A custom React hook that tracks the current window size and updates on resize.

useWindowSize is a custom React hook that tracks the current window size and provides real-time updates when the window is resized. This is particularly useful for creating responsive components that need to adapt to different screen sizes.

Example

Loading...

Install

npx shadcn@latest add https://unlogg.com/r/use-window-size.json
pnpm dlx shadcn@latest add https://unlogg.com/r/use-window-size.json
bunx shadcn@latest add https://unlogg.com/r/use-window-size.json

Notes

  • Automatically updates when the window is resized
  • Returns both width and height as numbers
  • Handles the resize event listener cleanup properly
  • Initializes with the current window size on mount

API Reference

Returns

PropTypeDefault
height?
number
-
width?
number
-

Usage

import { useWindowSize } from "@/hooks/use-window-size";

function ResponsiveComponent() {
  const { width, height } = useWindowSize();

  if (width < 768) {
    return <MobileView />;
  }

  return <DesktopView />;
}

Use Cases

  • Responsive Components: Create components that adapt based on screen size without relying solely on CSS media queries
  • Layout Calculations: Perform calculations that depend on the current viewport size
  • Performance Optimization: Conditionally render expensive components only on larger screens
  • Dynamic Styling: Apply different styles or behaviors based on window dimensions