useWindowSize()

Easily retrieve window dimensions with this Hook React which also works onRezise.

This hook uses useScreen internally.

The Hook

1// See: https://usehooks-typescript.com/react-hook/use-screen
2import { useScreen } from '~/hooks'
3
4interface WindowSize {
5 width: number
6 height: number
7}
8
9function useWindowSize(): WindowSize {
10 const screen = useScreen()
11
12 return {
13 width: screen?.width || 0,
14 height: screen?.height || 0,
15 }
16}
17
18export default useWindowSize

Usage

1import React from 'react'
2
3import useWindowSize from './useWindowSize'
4
5export default function Component() {
6 const { width, height } = useWindowSize()
7
8 return (
9 <div>
10 The current window dimensions are:{' '}
11 <code>{JSON.stringify({ width, height })}</code>
12 </div>
13 )
14}

Created:
10 months ago