forked from CredenceOrg/Credence-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseMediaQuery.ts
More file actions
52 lines (46 loc) · 1.54 KB
/
Copy pathuseMediaQuery.ts
File metadata and controls
52 lines (46 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { useEffect, useState } from 'react'
/**
* SSR-safe hook that subscribes to a CSS media query and returns whether it
* currently matches. The listener is cleaned up on unmount.
*
* @param query - A valid CSS media query string, e.g. `'(max-width: 767px)'`.
* @returns `true` while the query matches, `false` otherwise. Returns `false`
* in environments without `window.matchMedia` (SSR, Node test runners).
*
* @example
* ```tsx
* const isNarrow = useMediaQuery('(max-width: 767px)')
* return <span>{isNarrow ? 'Mobile' : 'Desktop'}</span>
* ```
*/
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState<boolean>(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return false
}
return window.matchMedia(query).matches
})
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return
}
const mql = window.matchMedia(query)
setMatches(mql.matches)
const handler = (event: MediaQueryListEvent) => setMatches(event.matches)
mql.addEventListener?.('change', handler)
return () => mql.removeEventListener?.('change', handler)
}, [query])
return matches
}
/**
* Returns `true` when the viewport is at the mobile breakpoint (< 768 px).
*
* @example
* ```tsx
* const isMobile = useIsMobile()
* return <h2>{isMobile ? 'Recent Activity' : 'Recent Activity Timeline'}</h2>
* ```
*/
export function useIsMobile(): boolean {
return useMediaQuery('(max-width: 767px)')
}