npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@usefy/use-window-size

v0.25.1

Published

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

Readme


Overview

@usefy/use-window-size is a React hook for tracking the browser window's dimensions in real time. It updates on every resize, supports debounce and throttle to limit update frequency, is safe to render on the server, and skips re-renders when the size hasn't actually changed.

Part of the @usefy ecosystem — a collection of production-ready React hooks designed for modern applications.

Why use-window-size?

  • Zero Dependencies — Pure React implementation with no external dependencies
  • TypeScript First — Full type safety with comprehensive type definitions
  • Debounce / Throttle — Limit how often updates fire during rapid resizes
  • SSR Compatible — Configurable initial size avoids hydration mismatches
  • No Wasted Renders — Bails out when width/height are unchanged
  • Scrollbar Control — Include or exclude the scrollbar in the measurement
  • onChange Callback — React to size changes imperatively
  • Well Tested — 100% test coverage with Vitest

Installation

# npm
npm install @usefy/use-window-size

# yarn
yarn add @usefy/use-window-size

# pnpm
pnpm add @usefy/use-window-size

Peer Dependencies

This package requires React 18 or 19:

{
  "peerDependencies": {
    "react": "^18.0.0 || ^19.0.0"
  }
}

Quick Start

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

| Parameter | Type | Description | | --------- | ---------------------- | ----------------------------- | | options | UseWindowSizeOptions | Optional configuration object |

Options

| Option | Type | Default | Description | | ------------------ | ------------------------------- | ------- | -------------------------------------------------------------------------------------------------------- | | initialWidth | number | 0 | Width returned before the window can be measured (SSR / first server render) | | initialHeight | number | 0 | Height returned before the window can be measured (SSR / first server render) | | debounceMs | number | 0 | Debounce resize updates by this many ms. Takes precedence over throttleMs | | throttleMs | number | 0 | Throttle resize updates to at most once per this many ms. Ignored when debounceMs is set | | includeScrollbar | boolean | true | true uses innerWidth/innerHeight (includes scrollbar); false uses documentElement client sizes | | enabled | boolean | true | When false, no resize listener is attached and the last known size is kept | | onChange | (size: WindowSize) => void | — | Callback fired whenever the window size changes |

Returns WindowSize

| Property | Type | Description | | -------- | -------- | --------------------------------- | | width | number | Current window width in pixels | | height | number | Current window height in pixels |

Exported Helpers

| Helper | Description | | ----------------------------------- | ----------------------------------------------------------------------- | | 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 |


Examples

Responsive Breakpoints

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

function Layout() {
  const { width } = useWindowSize();

  if (width < 640) return <MobileView />;
  if (width < 1024) return <TabletView />;
  return <DesktopView />;
}

Debounced Updates

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

function Chart() {
  // Only recompute the layout 200ms after the user stops resizing
  const { width, height } = useWindowSize({ debounceMs: 200 });

  return <Canvas width={width} height={height} />;
}

Throttled Updates with a Callback

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

function Sidebar() {
  const { width } = useWindowSize({
    throttleMs: 100,
    onChange: ({ width }) => {
      if (width < 768) closeSidebar();
    },
  });

  return <aside style={{ display: width < 768 ? "none" : "block" }} />;
}

SSR-Safe Initial Size

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

function App() {
  // Provide sensible defaults so server and first client render agree
  const { width, height } = useWindowSize({
    initialWidth: 1024,
    initialHeight: 768,
  });

  return <div>{width} × {height}</div>;
}

Excluding the Scrollbar

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

function Measurer() {
  // Uses document.documentElement.clientWidth/clientHeight
  const { width, height } = useWindowSize({ includeScrollbar: false });

  return <div>Content area: {width} × {height}</div>;
}

Freezing the Readout

import { useState } from "react";
import { useWindowSize } from "@usefy/use-window-size";

function ToggleTracking() {
  const [enabled, setEnabled] = useState(true);
  const { width, height } = useWindowSize({ enabled });

  return (
    <div>
      <button onClick={() => setEnabled((e) => !e)}>
        {enabled ? "Tracking" : "Frozen"}
      </button>
      {width} × {height}
    </div>
  );
}

TypeScript

This hook is written in TypeScript and exports comprehensive type definitions.

import {
  useWindowSize,
  type WindowSize,
  type UseWindowSizeOptions,
  type UseWindowSizeReturn,
  type OnWindowSizeChange,
} from "@usefy/use-window-size";

const size: WindowSize = useWindowSize({
  debounceMs: 200,
  onChange: ({ width, height }) => {
    console.log("Resized to", width, height);
  },
});

Performance

  • No-op Skipping — State is only updated when width or height actually change
  • Stable Listener — The resize handler reads the latest callback from a ref, so changing onChange never re-registers the listener
  • Debounce / Throttle — Rein in expensive re-renders during rapid resizes
  • Listener Cleanup — Automatically removes the listener and clears pending timers on unmount
  • SSR Compatible — Gracefully returns the configured initial size on the server

Browser Support

This hook uses window.innerWidth/innerHeight, document.documentElement, and the resize event — supported in all modern browsers:

  • Chrome 1+
  • Firefox 1+
  • Safari 1+
  • Edge 12+
  • Opera 7+

For SSR environments, the hook returns the configured initial size until it mounts on the client.


Testing

This package maintains comprehensive test coverage to ensure reliability and stability.

Test Coverage

📊 View Detailed Coverage Report (GitHub Pages)

Test Files

  • useWindowSize.test.ts — 25 tests for hook behavior and utilities

Total: 25 tests


License

MIT © mirunamu

This package is part of the usefy monorepo.