Implement a useWindowSize hook that returns the current height and width of the window (window.innerHeight and window.innerWidth). It should re-render the component if the screen properties changes.
export default function Component() {const screen = useWindowSize();return (<div><p>The current window dimensions are:</p><code>{JSON.stringify(screen, null, 2)}</code></div>);}
Nothing.
The hook returns an object with the following properties:
height: number: Current height of the screenwidth: number: Current width of the screenuseWindowSize returns a { width, height } snapshot of the current viewport. The hook's job is to keep that snapshot synchronized with the browser and to clean up its event listener when the component unmounts.
The main correctness concern is subscription timing. The hook should read the current size on mount, stay in sync with future resize events, and avoid leaving a listener behind.
useState stores the latest window-size snapshot because components render from it.useLayoutEffect performs the first read and attaches the resize listener before the browser paints.Using useLayoutEffect here avoids a brief paint with the placeholder { width: 0, height: 0 } state in the browser.
import { useState, useLayoutEffect } from 'react';/*** @typedef {Object} WindowSize* @property {number} height* @property {number} width*/export default function useWindowSize() {const [windowSize, setWindowSize] = useState({height: 0,width: 0,});useLayoutEffect(() => {const resize = () =>setWindowSize({height: window.innerHeight,width: window.innerWidth,});// Measure once on mount so consumers do not wait for the first resize event.resize();window.addEventListener('resize', resize);return () => {window.removeEventListener('resize', resize);};}, []);return windowSize;}
resize handler that was registered on mount.console.log() statements will appear here.