h3/use's logo

h3/use

Command Palette

Search for a command to run...

useWindowSize

Tracks the current window's dimensions.

useWindowSize
This component uses the useWindowSize hook to get the current window size.

Width: 1024

Height: 768

Resize the window to see the values changing.

Installation

Props

PropTypeDefaultDescription
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)

Data

PropTypeDescription
widthnumberThe current width of the window
heightnumberThe current height of the window

Key Features & Details

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.

Examples

Basic Usage

const { width, height } = useWindowSize();
return (
  <div>
    Window size: {width} x {height}
  </div>
);

With Initial Values (SSR-safe)

const { width, height } = useWindowSize({
  initialWidth: 1024,
  initialHeight: 768,
});

With onChange Callback

useWindowSize({
  onChange: (width, height) => {
    console.log('Window resized:', width, height);
  },
});