JAVASCRIPT

Track Real-time Window Dimensions with a Custom React Hook

Build a `useWindowSize` React hook to dynamically get the current width and height of the browser window, enabling responsive component rendering.

import { useState, useEffect, useCallback } from 'react';

const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: typeof window !== 'undefined' ? window.innerWidth : 0,
    height: typeof window !== 'undefined' ? window.innerHeight : 0,
  });

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

  useEffect(() => {
    // Only run if window is defined (e.g., in a browser environment)
    if (typeof window === 'undefined') {
      return;
    }

    window.addEventListener('resize', handleResize);

    // Call handler right away so state gets updated with initial window size
    handleResize();

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

  return windowSize;
};

export default useWindowSize;

// Example Usage:
/*
function ResponsiveText() {
  const { width } = useWindowSize();

  return (
    <p>
      Your window is {width}px wide. This text adapts based on screen size.
      {width < 768 ? ' (Mobile view)' : ' (Desktop view)'}
    </p>
  );
}
*/
How it works: The `useWindowSize` hook initializes state with the current `window.innerWidth` and `window.innerHeight`. It uses `useEffect` to add a `resize` event listener to the `window` object. The `handleResize` function, memoized with `useCallback` for stability, updates the state with new dimensions. The hook includes a cleanup function to remove the event listener and handles server-side rendering safely.

Need help integrating this into your project?

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

Hire DigitalCodeLabs