JAVASCRIPT

React Hook: useWindowSize to Track Browser Window Dimensions

Get real-time updates on browser window dimensions with the `useWindowSize` React hook. Essential for responsive layouts and components adapting to screen size changes.

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,
      });
    }

    // Set initial size immediately
    handleResize();

    window.addEventListener('resize', handleResize);

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

  return windowSize;
}
How it works: The `useWindowSize` hook tracks the browser's viewport dimensions. It initializes state with `undefined` for `width` and `height`. A `useEffect` hook is used to set up and clean up an event listener for the `resize` event on the `window` object. The `handleResize` function updates the state with the current `window.innerWidth` and `window.innerHeight`. The listener is added once on mount and removed on unmount, ensuring efficient resource management and providing real-time dimension updates to components using this hook.

Need help integrating this into your project?

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

Hire DigitalCodeLabs