JAVASCRIPT

Getting Real-time Window Dimensions with useWindowSize Hook

A custom React hook `useWindowSize` to effortlessly get the current width and height of the browser window for responsive component rendering.

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(); // Set initial size

    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();
//
//   if (width < 768) {
//     return <div>Mobile View ({width}px x {height}px)</div>;
//   }
//   return <div>Desktop View ({width}px x {height}px)</div>;
// }
How it works: The `useWindowSize` hook tracks the browser window's dimensions and provides them as a state object `{ width, height }`. It initializes the state to `undefined` and then uses a `useEffect` hook to add an event listener for the `resize` event. The `handleResize` function updates the state with the current `window.innerWidth` and `window.innerHeight`. The listener is added on mount and cleaned up on unmount, ensuring efficient subscription to window size changes and allowing components to re-render responsively.

Need help integrating this into your project?

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

Hire DigitalCodeLabs