JAVASCRIPT

Get Dynamic Window Dimensions in React

Access and react to changes in the browser window's dimensions with a custom `useWindowSize` React hook, enabling responsive UI components.

import { useState, useEffect } from 'react';

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

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

    window.addEventListener('resize', handleResize);
    handleResize(); // Call once to set initial size

    return () => window.removeEventListener('resize', handleResize);
  }, []); // Empty array ensures that effect is only run on mount and unmount

  return windowSize;
}
How it works: The `useWindowSize` hook provides the current `width` and `height` of the browser window. It initializes state with `undefined` and then uses `useEffect` to add a `resize` event listener to the `window` object. Whenever the window dimensions change, the state is updated, causing any consuming component to re-render with the new sizes. The cleanup function removes the event listener to prevent memory leaks, ensuring optimal performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs