JAVASCRIPT

Get Real-time Window Dimensions

A React hook to dynamically track and provide the current browser window's width and height, useful for creating responsive layouts and adapting UI components.

import { useState, useEffect } from 'react';

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

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

    window.addEventListener('resize', handleResize);
    handleResize(); // Set initial size

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

  return windowSize;
};

export default useWindowSize;
How it works: This custom hook initializes state with `undefined` dimensions, then uses a `useEffect` to attach a `resize` event listener to the window. The `handleResize` function updates the state with the current `innerWidth` and `innerHeight`. The effect cleans up the event listener on unmount, preventing memory leaks. It also calls `handleResize` once on mount to set the initial window size, making it immediately available to components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs