Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix useScreen on screen resize #474

Merged
merged 1 commit into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading