useScreen()

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

The Hook

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

Usage

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

Edit on CodeSandbox

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