Google Advertisement

Responsive React App with Custom Window Resize Hook

Google Advertisement
🔥 Read with Full Features on Our Website

Learn how to build a custom React hook to track window resize events and make your app fully responsive. Includes clear explanations and code samples.

Published on 14 May 2025
By Priya

 

🔥 Read with Full Features on Our Website

Responsiveness is no longer optional — users access your app from all types of devices and screen sizes. Whether you’re showing a mobile layout, adjusting components, or optimizing performance, tracking window size changes is a powerful tool in any React developer’s toolkit.

In this article, you’ll learn how to create a custom React hook that listens for window resize events, updates screen dimensions in real-time, and helps you build truly responsive components. We'll explain everything step by step, so even beginners can follow easily.


What You Will Learn


🧠 Basic Requirements

Before diving in, you should be familiar with:


🏗️ Step 1: Understanding window.innerWidth and window.innerHeight

The browser gives us two properties to track screen dimensions:

window.innerWidth;  // current width of the browser window
window.innerHeight; // current height of the browser window

You can also listen to the resize event like this:

window.addEventListener('resize', () => {
  console.log(window.innerWidth, window.innerHeight);
});

But in React, you need to encapsulate this logic cleanly — that’s where a custom hook comes in.


🧰 Step 2: Build the Custom Hook

Let’s create a new file named:
📁 src/hooks/useWindowSize.js

📄 useWindowSize.js

import { useState, useEffect } from 'react';

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

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

    // Add event listener
    window.addEventListener('resize', handleResize);

    // Call handler once to update state immediately
    handleResize();

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

  return windowSize;
}

export default useWindowSize;

But in React, you need to encapsulate this logic cleanly — that’s where a custom hook comes i

import { useState, useEffect } from 'react';

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

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

    // Add event listener
    window.addEventListener('resize', handleResize);

    // Call handler once to update state immediately
    handleResize();

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

  return windowSize;
}

export default useWindowSize;

Explanation (Line-by-Line)

Code Explanation
useState({...}) Initializes the state with current window size.
useEffect(() => {...}, []) Runs once on component mount. Adds the event listener.
handleResize() Updates the state whenever the window is resized.
addEventListener('resize', handleResize) Listens for window resize events.
return () => {...} Cleans up the event listener when the component unmounts.

Step 3: Use the Hook in a Component

Let’s create a component that shows the current window size using our custom hook.

📄 WindowSizeDisplay.js

import React from 'react';
import useWindowSize from './useWindowSize';

function WindowSizeDisplay() {
  const { width, height } = useWindowSize();

  return (
    <div style={{
      padding: '20px',
      textAlign: 'center',
      backgroundColor: '#f0f8ff',
      borderRadius: '8px',
      margin: '30px auto',
      width: 'fit-content',
      boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
    }}>
      <h2>📏 Window Size</h2>
      <p><strong>Width:</strong> {width}px</p>
      <p><strong>Height:</strong> {height}px</p>
    </div>
  );
}

export default WindowSizeDisplay;

🧩 Step 4: Add the Component to Your App

Now, let’s use this display component in your main App.js.

📄 App.js

import React from 'react';
import WindowSizeDisplay from './WindowSizeDisplay';

function App() {
  return (
    <div>
      <h1 style={{ textAlign: 'center' }}>React Window Resize Detector</h1>
      <WindowSizeDisplay />
    </div>
  );
}

export default App;

💡 Real-World Use Cases

Here are some common scenarios where a window resize hook is useful:

Use Case Description
📱 Responsive Layouts Dynamically change layout for mobile vs desktop
📦 Conditional Rendering Show/hide elements based on screen size
🗃️ Dynamic Grids Change number of columns depending on width
🎨 Canvas or Charts Resize chart or canvas elements on screen resize
🔄 Debounced Resize Combine with performance optimizations

⚠️ Best Practices

✅ Debouncing Resize Events

For performance, you can debounce the handleResize function using libraries like lodash:

npm install lodash

Then update your hook:

import { debounce } from 'lodash';
// inside useEffect
window.addEventListener('resize', debounce(handleResize, 300));

This ensures it doesn’t trigger resize events too frequently.


📦 Bonus: Return Only Width or Height (Optional)

Want only width or only height? Modify the hook like this:

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

You can do the same for height using useWindowHeight.


🧾 Conclusion

Creating a custom hook like useWindowSize in React gives you fine-grained control over responsiveness. Instead of relying on CSS media queries alone, you can use JavaScript logic to render components differently on different screen sizes.

This makes your apps more flexible, intelligent, and reactive to user environments. The hook is clean, reusable, and powerful — a must-have in your React toolbox.


🧩 Code Recap:

  • useWindowSize.js: Hook that returns { width, height }

  • WindowSizeDisplay.js: Uses the hook to display screen size

  • App.js: Integrates the component

 

 

 

❤️ Like 💬 Comment 🔗 Share
Google Advertisement
👉 View Full Version on Main Website ↗
Google Advertisement
👉 Read Full Article on Website