Rooks
HooksEvent Handling

useOnWindowResize

Calls a callback for passive window resize events.

About

useOnWindowResize runs a callback when window emits resize. It reports events; it does not return the current window dimensions.

Example

import { useState } from "react";
import { useOnWindowResize } from "rooks";

export default function ResizeReporter() {
  const [width, setWidth] = useState<number | null>(null);

  useOnWindowResize(() => {
    setWidth(window.innerWidth);
  });

  return <p>Last measured width: {width ?? "resize the window"}</p>;
}

Parameters

  • callback(event): receives the native resize Event.
  • when: enables the listener; defaults to true.
  • isLayoutEffect: subscribes during the layout-effect phase when true; defaults to false.

Return value

The hook returns void.

Behavior and lifecycle

The hook attaches a passive resize listener to window. Changing when to false removes it. The latest callback is used without requiring a new native listener; configuration changes replace the subscription, and unmount removes it.

Compatibility and accessibility

There is no window during server rendering, so no listener is attached. Resize events can fire rapidly and this hook does not throttle them; keep the callback small or combine it with a scheduling hook. Avoid reflow that moves focused content unexpectedly.

On this page