dotUI
dotUI
beta
  1. Hooks
  2. Elements hooks
  3. useWindowSize

useWindowSize

Track the dimensions of the browser window with useWindowSize.

"use client";

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

function Demo() {
  const size = useWindowSize();

  return (
    <div>
      <p className="text-center text-xl font-bold">Resize your window</p>
      <div className="mt-4 grid grid-cols-2 gap-8">
        <div>
          <p className="text-fg-muted">width</p>
          <p className="text-xl">{size.width}px</p>
        </div>
        <div>
          <p className="text-fg-muted">height</p>
          <p className="text-xl">{size.height}px</p>
        </div>
      </div>
    </div>
  );
}

Installation

Copy and paste the following code into your project.

import React from "react";

export function useWindowSize() {
  const [size, setSize] = React.useState<{
    width: number | null;
    height: number | null;
  }>({
    width: null,
    height: null,
  });

  React.useLayoutEffect(() => {
    const handleResize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    handleResize();
    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return size;
}

Update the import paths to match your project setup.

Return values

NameTypeDescription
width
number
The current width of the window, in pixels.
height
number
The current height of the window, in pixels.

Built by mehdibha. The source code is available on GitHub.