Open History to see the last commit
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()
44}