Skip to content

useWidth

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

useWidth

A simple, performant hook to track the global inner window width dynamically. It safely handles server-side rendering (SSR) and automatically debounces window resize events to prevent your React app from lagging during manual window resizing.

Usage Examples

Basic

Dynamically conditionally rendering a Mobile or Desktop navigation component.

import { useWidth } from "react-hook-lab";

function AppNavigation() {
  const width = useWidth();
  
  // Conditionally render entirely different component trees based on width
  const isMobile = width < 768;

  return (
    <nav>
      {isMobile ? <HamburgerMenu /> : <FullDesktopMenu />}
    </nav>
  );
}

Common

Adjusting complex layout props (like grid columns or chart data points) that CSS media queries cannot easily handle.

import { useWidth } from "react-hook-lab";
import { DataGrid } from "./components";

function DashboardData() {
  const width = useWidth();

  let columns = 1;
  if (width >= 768) columns = 2;
  if (width >= 1024) columns = 4;

  return <DataGrid columns={columns} data={[]} />;
}

API Reference

Return Type

Returns a number representing the current window.innerWidth in pixels. (Note: If called on the server where window is undefined, it safely returns 0).

Core Working

On mount, useWidth grabs the initial window.innerWidth. It attaches a "resize" event listener to the global window object. However, native resize events can fire dozens of times per second, which would absolutely tank React's render performance.

To prevent jank, this hook utilizes a built-in setTimeout debounce mechanism (150ms). When the user is dragging the edge of their browser window, the hook waits until they pause for at least 150 milliseconds before it actually triggers a React state update and re-renders your components.

Clone this wiki locally