Skip to content

Commit

Permalink
♻️ Removed the need of commenting out useEffect deps (#383)
Browse files Browse the repository at this point in the history
* Removed the need of commenting out useEffect deps

* 🔖 Add changeset

---------

Co-authored-by: Lisandro Cobeaga <lisandro.cobeaga@inworx.com>
Co-authored-by: Julien <juliencaron@protonmail.com>
  • Loading branch information
3 people authored Jan 19, 2024
1 parent ee260c8 commit 42f3a3a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/calm-stingrays-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"usehooks-ts": patch
---

Remove the need of commenting out useEffect deps in useMediaQuery (#383 by @lisandro52)
23 changes: 11 additions & 12 deletions packages/usehooks-ts/src/useMediaQuery/useMediaQuery.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { useEffect, useState } from 'react'

export function useMediaQuery(query: string): boolean {
const getMatches = (query: string): boolean => {
// Prevents SSR issues
if (typeof window !== 'undefined') {
return window.matchMedia(query).matches
}
return false
const getMatches = (query: string): boolean => {
// Prevents SSR issues
if (typeof window !== 'undefined') {
return window.matchMedia(query).matches
}
return false
}

export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState<boolean>(getMatches(query))

function handleChange() {
setMatches(getMatches(query))
}

useEffect(() => {
function handleChange() {
setMatches(getMatches(query))
}

const matchMedia = window.matchMedia(query)

// Triggered at the first client-side load and if query changes
Expand All @@ -35,7 +35,6 @@ export function useMediaQuery(query: string): boolean {
matchMedia.removeEventListener('change', handleChange)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query])

return matches
Expand Down

0 comments on commit 42f3a3a

Please sign in to comment.