JAVASCRIPT
React `useWindowSize` Hook for Dynamic Layouts
A custom React hook to track and provide the current width and height of the browser window, useful for building responsive layouts and components.
import { useState, useEffect } from 'react';
const useWindowSize = () => {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
const handleResize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
window.addEventListener('resize', handleResize);
handleResize(); // Set initial size
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return windowSize;
};
export default useWindowSize;
/* Example Usage:
import React from 'react';
function MyComponent() {
const { width, height } = useWindowSize();
return (
<div>
<p>Window Width: {width}px</p>
<p>Window Height: {height}px</p>
{width && width < 768 && <p>This content is only visible on small screens!</p>}
</div>
);
}
*/
How it works: This hook provides the current `width` and `height` of the browser window. It initializes the state with the current window dimensions and then updates it whenever the window is resized, using an `addEventListener` for the 'resize' event. This is essential for components that need to adjust their behavior or rendering based on the viewport size.