useScreen()

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

The Hook

1import { useEffect, useState } from 'react'
2
3function useScreen() {
4 const getScreen = () => {
5 if (typeof window !== 'undefined' && window.screen) {
6 return window.screen
7 }
8 return undefined
9 }
10
11 const [screen, setScreen] = useState<Screen | undefined>(getScreen())
12
13 useEffect(() => {
14 function handleResize() {
15 setScreen(getScreen())
16 }
17
18 window.addEventListener('resize', handleResize)
19 return () => {
20 window.removeEventListener('resize', handleResize)
21 }
22 // Empty array ensures that effect is only run on mount and unmount
23 }, [])
24
25 return screen
26}
27
28export 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}

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