JAVASCRIPT

Track Window Dimensions with a `useWindowSize` Hook

Implement a `useWindowSize` React hook to get real-time width and height of the browser window, enabling dynamic and responsive UI adjustments.

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 on mount and unmount

  return windowSize;
}

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

//   return (
//     <div>
//       <p>Window Width: {width}px</p>
//       <p>Window Height: {height}px</p>
//       {width < 768 ? <p>Small Screen Mode</p> : <p>Large Screen Mode</p>}
//     </div>
//   );
// }
How it works: The `useWindowSize` hook provides the current width and height of the browser window, updating these values whenever the window is resized. It uses `useState` to store the dimensions and `useEffect` to attach and clean up a 'resize' event listener. This hook is valuable for creating responsive designs or adjusting component behavior based on available screen space, offering real-time dimension data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs