← Back to all snippets
JAVASCRIPT

Tracking Window Dimensions with useWindowSize Hook

Create a `useWindowSize` React hook to efficiently track and respond to changes in the browser window's width and height, crucial for responsive UIs.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    // Handler to call on window resize
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }

    // Add event listener
    window.addEventListener('resize', handleResize);

    // Call handler right away so state gets updated with initial window size
    handleResize();

    // Remove event listener on cleanup
    return () => window.removeEventListener('resize', handleResize);
  }, []); // Empty array ensures that effect is only run once on mount

  return windowSize;
}

// Example Usage:
/*
function ResponsiveComponent() {
  const { width, height } = useWindowSize();

  return (
    <div>
      <p>Window Width: {width}</p>
      <p>Window Height: {height}</p>
      {width < 768 ? <p>Small Screen Mode</p> : <p>Large Screen Mode</p>}
    </div>
  );
}
*/
How it works: The `useWindowSize` hook initializes state with the current `window.innerWidth` and `window.innerHeight`. A `useEffect` hook then sets up a `resize` event listener on the `window` object. The `handleResize` function updates the state with the new dimensions whenever the window is resized. The effect is set to run only once on mount (`[]` dependency array) and includes a cleanup function to remove the event listener, preventing performance issues and memory leaks. It also calls `handleResize` initially to set the correct dimensions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs