forked from excalidraw/excalidraw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
is-mobile.tsx
31 lines (26 loc) · 971 Bytes
/
is-mobile.tsx
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
import React, { useState, useEffect, useRef, useContext } from "react";
const context = React.createContext(false);
export function IsMobileProvider({ children }: { children: React.ReactNode }) {
const query = useRef<MediaQueryList>();
if (!query.current) {
query.current = window.matchMedia
? window.matchMedia(
"(max-width: 640px), (max-height: 500px) and (max-width: 1000px)",
)
: (({
matches: false,
addListener: () => {},
removeListener: () => {},
} as any) as MediaQueryList);
}
const [isMobile, setMobile] = useState(query.current.matches);
useEffect(() => {
const handler = () => setMobile(query.current!.matches);
query.current!.addListener(handler);
return () => query.current!.removeListener(handler);
}, []);
return <context.Provider value={isMobile}>{children}</context.Provider>;
}
export default function useIsMobile() {
return useContext(context);
}