Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

useMediaQuery.ts

44 lines1.1 KB

1import { createEffect, createSignal } from 'solid-js'
2import type { Accessor } from 'solid-js'
3​
4export default function useMediaQuery(
5 query: string,
6): Accessor<boolean | undefined> {
7 // Keep track of the preference in state, start with the current match
8 const [isMatch, setIsMatch] = createSignal(() => {
9 if (typeof window !== 'undefined') {
10 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
11 return window.matchMedia && window.matchMedia(query).matches
12 }
13 return
14 })
15​
16 // Watch for changes
17 createEffect(() => {
18 if (typeof window !== 'undefined') {
19 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
20 if (!window.matchMedia) {
21 return
22 }
23​
24 // Create a matcher
25 const matcher = window.matchMedia(query)
26​
27 // Create our handler
28 const onChange = ({ matches }: { matches: boolean }) =>
29 setIsMatch(() => () => matches)
30​
31 // Listen for changes
32 matcher.addListener(onChange)
33​
34 return () => {
35 // Stop listening for changes
36 matcher.removeListener(onChange)
37 }
38 }
39​
40 return
41 })
42​
43 return isMatch()