useScreen()

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

The Hook

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