useWindowSize

A React hook that tracks window dimensions in real-time, providing responsive width and height values with TypeScript support. Perfect for creating responsive layouts and handling window resize events efficiently.

Interactive Demo

Window Width

0px

Window Height

0px

Try resizing your browser window to see the values update in real-time!

Implementation

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

export function useWindowSize(): WindowSize {
  const [windowSize, setWindowSize] = useState<WindowSize>({
    width: typeof window !== "undefined" ? window.innerWidth : 0,
    height: typeof window !== "undefined" ? window.innerHeight : 0,
  });

  useEffect(() => {
    if (typeof window === "undefined") return;

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

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

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

  return windowSize;
}

Usage Examples

import { useWindowSize } from '@/components/hooks/useWindowSize';

function ResponsiveComponent() {
  const { width, height } = useWindowSize();
  
  return (
    <div>
      <p>Current window dimensions:</p>
      <p>Width: {width}px</p>
      <p>Height: {height}px</p>
      {width < 768 && (
        <p>Mobile view detected!</p>
      )}
    </div>
  );
}

Documentation

Key Features

  • Real-time window dimension tracking
  • TypeScript support with proper typing
  • SSR compatible
  • Efficient resize event handling
  • Automatic cleanup of event listeners

Common Use Cases

  • Responsive layouts
  • Conditional rendering based on window size
  • Dynamic styling calculations
  • Mobile/desktop detection
  • Canvas and visualization sizing

API Reference

useWindowSize(): WindowSize

Returns an object containing the current window dimensions.

Return Value:

  • width: number - Current window width in pixels
  • height: number - Current window height in pixels

Browser Compatibility

The hook uses standard window resize events and innerWidth/innerHeight properties, which are supported in all modern browsers. For older browsers, consider using a polyfill for window.innerWidth and window.innerHeight.