UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

33 lines 1.3 kB
import { useState, useEffect } from 'react'; /** * Custom hook that tracks the browser window's dimensions. * * @returns {WindowSize} An object containing the current window width and height. * Returns { width: undefined, height: undefined } on the server-side. */ export const useWindowSize = () => { // Initialize state with undefined width/height so server and client renders match // Prevent hydration warning const [windowSize, setWindowSize] = useState({ width: undefined, height: undefined, }); useEffect(() => { // Handler to call on window resize function handleResize() { // Set window width/height to state setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); } // Add event listener window.addEventListener('resize', handleResize); // Call handler right away so state gets updated with initial window size handleResize(); // Remove event listener on cleanup return () => window.removeEventListener('resize', handleResize); }, []); // Empty array ensures that effect is only run on mount and unmount return windowSize; }; //# sourceMappingURL=useWindowSize.js.map