JAVASCRIPT
Create a Custom Hook to Track Window Dimensions
Build a reusable custom React hook, useWindowSize, that provides the current browser window's width and height, enabling responsive designs and conditional rendering.
import React, { 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;
}
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
window.addEventListener('resize', handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Cleanup function
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty array ensures effect runs once on mount and cleans up on unmount
return windowSize;
}
// Example component using the hook
function ResponsiveComponent() {
const { width, height } = useWindowSize();
return (
<div>
<h1>Window Size</h1>
<p>Width: {width}px</p>
<p>Height: {height}px</p>
{width < 768 ? <p>You are on a small screen device.</p> : <p>You are on a large screen device.</p>}
</div>
);
}
export default ResponsiveComponent;
export { useWindowSize }; // Exporting for reuse
How it works: The `useWindowSize` custom hook tracks and provides the current dimensions of the browser window. It utilizes `useState` to store the width and height, and `useEffect` to add and remove a 'resize' event listener. The effect runs once on mount, attaching the listener, and returns a cleanup function that removes the listener when the component unmounts, preventing memory leaks. This hook is highly useful for building responsive UIs that adapt based on the screen size, allowing for conditional rendering or dynamic styling.