JAVASCRIPT

Custom useWindowSize Hook to Track Window Dimensions

Develop a `useWindowSize` custom React hook to efficiently track and provide the current browser window's width and height for responsive components.

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(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }

    // Only add listener if window is defined (client-side)
    if (typeof window !== 'undefined') {
      window.addEventListener('resize', handleResize);
      handleResize(); // Set initial size

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

  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</p> : <p>Large Screen</p>}
//     </div>
//   );
// }
How it works: The `useWindowSize` hook provides the current width and height of the browser window, updating them whenever the window is resized. It uses `useState` to store the dimensions and `useEffect` to add and remove a `resize` event listener on the `window` object. This hook is crucial for creating responsive components that adapt their layout or content based on screen dimensions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs