Skip to content

Commit

Permalink
🐛 Fix useScreen on screen resize (#474)
Browse files Browse the repository at this point in the history
  • Loading branch information
juliencrn authored Feb 6, 2024
1 parent a444ba7 commit be8c35b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/young-rockets-marry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'usehooks-ts': patch
---

Fix `useScreen` is not rerendering on screen resize (#280 by @philipgher)
34 changes: 32 additions & 2 deletions packages/usehooks-ts/src/useScreen/useScreen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,46 @@ export function useScreen(
initializeWithValue = false
}

const readScreen = () => {
if (IS_SERVER) {
return undefined
}
return window.screen
}

const [screen, setScreen] = useState<Screen | undefined>(() => {
if (initializeWithValue) {
return window.screen
return readScreen()
}
return undefined
})

/** Handles the resize event of the window. */
function handleSize() {
setScreen(window.screen)
const newScreen = readScreen()

if (newScreen) {
// Create a shallow clone to trigger a re-render (#280).
const {
width,
height,
availHeight,
availWidth,
colorDepth,
orientation,
pixelDepth,
} = newScreen

setScreen({
width,
height,
availHeight,
availWidth,
colorDepth,
orientation,
pixelDepth,
})
}
}

useEventListener('resize', handleSize)
Expand Down

0 comments on commit be8c35b

Please sign in to comment.