useWindowSize()
Easily retrieve window dimensions with this React Hook which also works onResize.
The Hook
1import { useState } from 'react'23import { useEventListener, useIsomorphicLayoutEffect } from 'usehooks-ts'45interface WindowSize {6 width: number7 height: number8}910function useWindowSize(): WindowSize {11 const [windowSize, setWindowSize] = useState<WindowSize>({12 width: 0,13 height: 0,14 })1516 const handleSize = () => {17 setWindowSize({18 width: window.innerWidth,19 height: window.innerHeight,20 })21 }2223 useEventListener('resize', handleSize)2425 // Set size at the first client-side load26 useIsomorphicLayoutEffect(() => {27 handleSize()28 // eslint-disable-next-line react-hooks/exhaustive-deps29 }, [])3031 return windowSize32}3334export default useWindowSize
Usage
1import { useWindowSize } from 'usehooks-ts'23export default function Component() {4 const { width, height } = useWindowSize()56 return (7 <div>8 The current window dimensions are:{' '}9 <code>{JSON.stringify({ width, height })}</code>10 </div>11 )12}
See a way to make this page better?
Edit there »