Skip to content

Commit

Permalink
🐛 Fix setMatches hook in useMediaQuery by defining getMatches before …
Browse files Browse the repository at this point in the history
…use (#494)

* Fix setMatches hook by defining getMatches before use

* Add changelog

* Update priority
  • Loading branch information
ymc-maha committed Feb 20, 2024
1 parent a667b19 commit 6514683
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/real-foxes-fold.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"usehooks-ts": patch
---

Fix setMatches hook in useMediaQuery by defining getMatches before use
14 changes: 7 additions & 7 deletions packages/usehooks-ts/src/useMediaQuery/useMediaQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,20 @@ export function useMediaQuery(
? undefined
: options?.initializeWithValue ?? undefined

const [matches, setMatches] = useState<boolean>(() => {
if (initializeWithValue) {
return getMatches(query)
}
return defaultValue
})

const getMatches = (query: string): boolean => {
if (IS_SERVER) {
return defaultValue
}
return window.matchMedia(query).matches
}

const [matches, setMatches] = useState<boolean>(() => {
if (initializeWithValue) {
return getMatches(query)
}
return defaultValue
})

/** Handles the change event of the media query. */
function handleChange() {
setMatches(getMatches(query))
Expand Down

0 comments on commit 6514683

Please sign in to comment.