How to Create useWindowSize Hook in React for Responsive Design
Create a
useWindowSize hook in React by using useState to store window dimensions and useEffect to add a resize event listener that updates the state. This hook returns the current width and height of the window, allowing components to respond to size changes.Syntax
The useWindowSize hook uses React's useState to hold the window's width and height, and useEffect to set up and clean up the resize event listener.
- useState: Stores the current window size.
- useEffect: Runs once to add the resize listener and cleans it up on unmount.
- Event listener: Updates state when the window is resized.
- Return value: An object with
widthandheight.
javascript
import { useState, useEffect } from 'react'; function useWindowSize() { const [windowSize, setWindowSize] = useState({ width: typeof window === 'undefined' ? 0 : window.innerWidth, height: typeof window === 'undefined' ? 0 : window.innerHeight }); useEffect(() => { function handleResize() { setWindowSize({ width: window.innerWidth, height: window.innerHeight }); } window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return windowSize; }
Example
This example shows a React component using the useWindowSize hook to display the current window width and height. The displayed values update live as you resize the browser window.
javascript
import React from 'react'; import { useState, useEffect } from 'react'; function useWindowSize() { const [windowSize, setWindowSize] = useState({ width: typeof window === 'undefined' ? 0 : window.innerWidth, height: typeof window === 'undefined' ? 0 : window.innerHeight }); useEffect(() => { function handleResize() { setWindowSize({ width: window.innerWidth, height: window.innerHeight }); } window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return windowSize; } export default function WindowSizeDisplay() { const { width, height } = useWindowSize(); return ( <div style={{ fontFamily: 'Arial, sans-serif', padding: '1rem' }}> <h2>Window Size</h2> <p> Width: <strong>{width}px</strong><br /> Height: <strong>{height}px</strong> </p> </div> ); }
Output
Window Size
Width: 1024px
Height: 768px
(Updates live as window resizes)
Common Pitfalls
Common mistakes when creating useWindowSize include:
- Accessing
windowdirectly during server-side rendering, causing errors. - Not cleaning up the event listener, leading to memory leaks.
- Updating state too often or unnecessarily causing performance issues.
To avoid these, check if window exists before using it, and always remove event listeners in the cleanup function.
javascript
import { useState, useEffect } from 'react'; // Wrong: Accessing window without check and no cleanup function useWindowSizeWrong() { const [size, setSize] = useState({ width: typeof window === 'undefined' ? 0 : window.innerWidth, height: typeof window === 'undefined' ? 0 : window.innerHeight }); useEffect(() => { window.addEventListener('resize', () => { setSize({ width: window.innerWidth, height: window.innerHeight }); }); }, []); return size; } // Right: Check window and cleanup function useWindowSizeRight() { const isClient = typeof window === 'object'; const [size, setSize] = useState({ width: isClient ? window.innerWidth : 0, height: isClient ? window.innerHeight : 0 }); useEffect(() => { if (!isClient) return; function handleResize() { setSize({ width: window.innerWidth, height: window.innerHeight }); } window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, [isClient]); return size; }
Quick Reference
useWindowSize Hook Cheat Sheet:
| Step | Purpose |
|---|---|
| Initialize state | Store window width and height |
| useEffect setup | Add resize event listener once |
| Event handler | Update state on resize |
| Cleanup | Remove event listener on unmount |
| Return | Current window size object |
| Step | Purpose |
|---|---|
| Initialize state | Store window width and height |
| useEffect setup | Add resize event listener once |
| Event handler | Update state on resize |
| Cleanup | Remove event listener on unmount |
| Return | Current window size object |
Key Takeaways
Use useState to store window width and height inside the hook.
Add and clean up the resize event listener inside useEffect to avoid memory leaks.
Check if window exists to prevent errors during server-side rendering.
Return an object with width and height for easy use in components.
Update state only when the window resizes to keep components responsive.