useScreen()

Easily retrieve window.screen object with this Hook React which also works onResize.

The Hook

1import { useState } from 'react'
2
3import { useEventListener, useIsomorphicLayoutEffect } from 'usehooks-ts'
4
5function useScreen() {
6 const getScreen = () => {
7 if (typeof window !== 'undefined' && window.screen) {
8 return window.screen
9 }
10 return undefined
11 }
12
13 const [screen, setScreen] = useState<Screen | undefined>(getScreen())
14
15 function handleSize() {
16 setScreen(getScreen())
17 }
18
19 useEventListener('resize', handleSize)
20
21 // Set size at the first client-side load
22 useIsomorphicLayoutEffect(() => {
23 handleSize()
24 // eslint-disable-next-line react-hooks/exhaustive-deps
25 }, [])
26
27 return screen
28}
29
30export default useScreen

Usage

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

Edit on CodeSandbox

See a way to make this page better?
Edit there »