DOM

useWindowSize

Tracks the viewport's { width, height }, updated on resize.

Demo

width
height
breakpoint

Resize the window — both values update on every resize event, and the breakpoint label tracks Tailwind’s default ladder.

Usage

use-window-size.tsxtsx
import { useWindowSize } from "hookli";

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

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

API

useWindowSize.d.tsts
useWindowSize(options?: UseWindowSizeOptions): WindowSize

Parameters

NameTypeDefaultDescription
optionsUseWindowSizeOptions{}Hydration behaviour. Optional.

Returns

NameTypeDescription
widthnumberThe viewport's inner width in pixels. 0 on the server and until hydration.
heightnumberThe viewport's inner height in pixels. 0 on the server and until hydration.

WindowSize

The viewport size reported by useWindowSize.

NameTypeDescription
widthnumberThe viewport's inner width in pixels.
heightnumberThe viewport's inner height in pixels.

UseWindowSizeOptions

Configures mount behaviour.

NameTypeDescription
initializeWithValuebooleanRead the real size synchronously on mount. Set false to start at 0 and populate after hydration.

Hook

The implementation, straight from hookli. Copy it, or install the package.

src/hooks/use-window-size/use-window-size.tstsx
import { useState } from "react";
import { useEventListener } from "../use-event-listener/use-event-listener";
import { useIsomorphicLayoutEffect } from "../use-isomorphic-layout-effect/use-isomorphic-layout-effect";

interface WindowSize {
  width: number;
  height: number;
}

interface UseWindowSizeOptions {
  initializeWithValue?: boolean;
}

const IS_SERVER = typeof window === "undefined";

export function useWindowSize(options: UseWindowSizeOptions = {}): WindowSize {
  const { initializeWithValue = true } = options;

  const readSize = (): WindowSize => ({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  const [windowSize, setWindowSize] = useState<WindowSize>(() => {
    if (initializeWithValue && !IS_SERVER) return readSize();
    return { width: 0, height: 0 };
  });

  const handleSize = () => {
    if (IS_SERVER) return;
    setWindowSize(readSize());
  };

  useEventListener("resize", handleSize);

  useIsomorphicLayoutEffect(() => {
    handleSize();
  }, []);

  return windowSize;
}

View source on GitHub

Related hooks