Skip to content
usefy

useWindowSize

Browser & device

A React hook for tracking the browser window size with debounce/throttle and SSR support

Install

$ npm install @usefy/use-window-size

Quick start

useWindowSize.tsx
import { useWindowSize } from "@usefy/use-window-size";

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

  return (
    <div>
      {width} × {height}
      {width < 768 ? <MobileView /> : <DesktopView />}
    </div>
  );
}

API reference

useWindowSize(options?)

A hook that tracks the browser window size and returns { width, height }.

Parameters

ParameterTypeDescription
optionsUseWindowSizeOptionsOptional configuration object

Options

OptionTypeDefaultDescription
initialWidthnumber0Width returned before the window can be measured (SSR / first server render)
initialHeightnumber0Height returned before the window can be measured (SSR / first server render)
debounceMsnumber0Debounce resize updates by this many ms. Takes precedence over throttleMs
throttleMsnumber0Throttle resize updates to at most once per this many ms. Ignored when debounceMs is set
includeScrollbarbooleantruetrue uses innerWidth/innerHeight (includes scrollbar); false uses documentElement client sizes
enabledbooleantrueWhen false, no resize listener is attached and the last known size is kept
onChange(size: WindowSize) => voidCallback fired whenever the window size changes

Returns WindowSize

PropertyTypeDescription
widthnumberCurrent window width in pixels
heightnumberCurrent window height in pixels

Exported Helpers

HelperDescription
isWindowAvailable()Returns true in a browser environment, false in SSR
getWindowSize(includeScrollbar?)Reads the current window size (returns { width: 0, height: 0 } in SSR)
areSizesEqual(a, b)Compares two WindowSize values for equality

Go deeper

This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.

More in browser & device