Let's create a custom useViewportSize hook in React that tracks the viewport dimensions (width and height) and updates them on window resize. This hook is useful for responsive design and dynamic layouts.
Here's the implementation:
import { useState, useEffect } from 'react';
function useViewportSize() {
// Initialize state with current window dimensions
const [viewportSize, setViewportSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
// Handler to update viewport size
const handleResize = () => {
setViewportSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
// Add event listener for window resize
window.addEventListener('resize', handleResize);
// Cleanup: remove event listener on component unmount
return () => {
window.removeEventListener('resize', handleResize);
};
}, []); // Empty dependency array means this effect runs once on mount
return viewportSize;
}
export default useViewportSize;
Here's how to use the hook in a component:
import React from 'react';
import useViewportSize from './useViewportSize';
function MyComponent() {
const { width, height } = useViewportSize();
return (
<div>
<h1>Viewport Dimensions</h1>
<p>Width: {width}px</p>
<p>Height: {height}px</p>
{/* Example of using the dimensions for responsive design */}
<div style={{
backgroundColor: 'lightblue',
width: width > 768 ? '50%' : '100%',
height: '200px',
margin: '0 auto'
}}>
Responsive Container
</div>
</div>
);
}
export default MyComponent;
Let's break down how the hook works:
-
State Management:
- We use
useState to create a state object containing width and height
- Initial values are set to the current window dimensions using
window.innerWidth and window.innerHeight
-
Effect Hook:
useEffect is used to handle the side effect of adding/removing the resize event listener
- The effect runs only once on mount (empty dependency array
[])
- It sets up a resize event listener that updates the state when the window is resized
-
Cleanup:
- The cleanup function in
useEffect removes the event listener when the component unmounts
- This prevents memory leaks and multiple event listeners from being added
-
Return Value:
- The hook returns an object with
width and height properties
- Components using the hook can destructure these values
Here's an enhanced version of the hook that includes debouncing to improve performance by limiting how often the state updates during continuous resizing:
import { useState, useEffect } from 'react';
function useViewportSize(debounceDelay = 200) {
const [viewportSize, setViewportSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
let timeoutId;
// Handler to update viewport size with debouncing
const handleResize = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
setViewportSize({
width: window.innerWidth,
height: window.innerHeight,
});
}, debounceDelay);
};
// Add event listener for window resize
window.addEventListener('resize', handleResize);
// Cleanup: remove event listener and clear timeout
return () => {
window.removeEventListener('resize', handleResize);
clearTimeout(timeoutId);
};
}, [debounceDelay]); // Re-run effect if debounceDelay changes
return viewportSize;
}
export default useViewportSize;
Usage of the debounced version:
import React from 'react';
import useViewportSize from './useViewportSize';
function MyComponent() {
// Use the hook with a custom debounce delay (optional)
const { width, height } = useViewportSize(300);
return (
<div>
<h1>Viewport Dimensions (Debounced)</h1>
<p>Width: {width}px</p>
<p>Height: {height}px</p>
</div>
);
}
export default MyComponent;
Key features of the enhanced version:
-
Debouncing:
- Added a
debounceDelay parameter (defaults to 200ms)
- Uses
setTimeout and clearTimeout to debounce the resize updates
- Improves performance by reducing the number of state updates during rapid resizing
-
Configurability:
- The debounce delay can be customized when using the hook
- The dependency array includes
debounceDelay to ensure the effect updates if the delay changes
This hook is particularly useful for:
- Creating responsive layouts
- Triggering different behaviors based on viewport size
- Building mobile-first or desktop-first designs
- Optimizing rendering performance in resize-heavy applications
Remember to handle server-side rendering (SSR) cases if you're using this in a framework like Next.js, where window might not be available during initial render. You might want to add a check for typeof window !== 'undefined' in such cases.