useWindowSize()
Easily retrieve window dimensions with this React Hook which also works onRezise.
The Hook
1import { useState } from 'react'23// See: https://usehooks-ts.com/react-hook/use-event-listener4import { useEventListener } from '../useEventListener'5// See: https://usehooks-ts.com/react-hook/use-isomorphic-layout-effect6import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect'78interface WindowSize {9 width: number10 height: number11}1213function useWindowSize(): WindowSize {14 const [windowSize, setWindowSize] = useState<WindowSize>({15 width: 0,16 height: 0,17 })1819 const handleSize = () => {20 setWindowSize({21 width: window.innerWidth,22 height: window.innerHeight,23 })24 }2526 useEventListener('resize', handleSize)2728 // Set size at the first client-side load29 useIsomorphicLayoutEffect(() => {30 handleSize()31 // eslint-disable-next-line react-hooks/exhaustive-deps32 }, [])3334 return windowSize35}3637export default useWindowSize
Usage
1import React from 'react'23import { useWindowSize } from 'usehooks-ts'45export default function Component() {6 const { width, height } = useWindowSize()78 return (9 <div>10 The current window dimensions are:{' '}11 <code>{JSON.stringify({ width, height })}</code>12 </div>13 )14}
See a way to make this page better?
Edit there »