← Back to all snippets
JAVASCRIPT

Custom `useWindowSize` Hook for Responsive Components

Create a custom React `useWindowSize` hook to track the current width and height of the browser window, enabling dynamic and responsive UI adjustments in your 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(() => {
    // Only run on client-side
    if (typeof window === 'undefined') {
      return; // Server-side rendering, do nothing
    }

    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 once on mount and cleanup on 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 Layout</p> : <p>Large Screen Layout</p>}
//     </div>
//   );
// }
How it works: The `useWindowSize` hook tracks the browser window's `width` and `height`. It initializes its state with the current window dimensions, handling server-side rendering gracefully by defaulting to 0. An `useEffect` hook adds a `resize` event listener to the `window` object. The `handleResize` function updates the state with new dimensions whenever the window size changes. The effect runs once on mount, and its cleanup function ensures the event listener is removed when the component unmounts, preventing memory leaks. This hook is ideal for creating responsive components that adapt their layout or content based on the viewport size.

Need help integrating this into your project?

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

Hire DigitalCodeLabs