Skip to content

useWindowSize

React hook to track the dimensions of the browser window.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useWindowSize
sh
npx @novajslabs/cli add useWindowSize
sh
pnpm dlx @novajslabs/cli add useWindowSize

Or copy and paste the code into your project:

ts
import { useState, useEffect } from "react";

type WindowSize = {
  width: number;
  height: number;
};

export const useWindowSize = (): WindowSize => {
  const [windowSize, setWindowSize] = useState<WindowSize>({
    width: window.innerWidth,
    height: window.innerHeight,
  });

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

  useEffect(() => {
    window.addEventListener("resize", handleResize);

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

  return windowSize;
};
js
import { useState, useEffect } from "react";

export const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

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

  useEffect(() => {
    window.addEventListener("resize", handleResize);

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

  return windowSize;
};

Requirements

React 16.8 or higher

Return values

width

Type: number

The current width of the browser window in pixels.

height

Type: number

The current height of the browser window in pixels.

Example

tsx
import { useWindowSize } from "./hooks/useWindowSize";

const App = () => {
  const { width, height } = useWindowSize();

  return (
    <div className={`${width > 1200 ? "w-96" : "w-56"}`}>Some content</div>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Dynamically resizing elements or components based on changes in the viewport size
  • Adapting the display of content or media based on the available screen space in a mobile-responsive website
  • Implementing conditional rendering of UI elements for different device sizes in a cross-platform application
  • Adjusting the positioning or alignment of elements based on changes in the browser window dimensions for improved user experience

Released under the MIT License.