Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

use-mobile.ts

21 lines585 Bytes

1import * as React from "react";
2​
3const MOBILE_BREAKPOINT = 768;
4​
5export function useIsMobile() {
6 const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
7 undefined,
8 );
9​
10 React.useEffect(() => {
11 const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
12 const onChange = () => {
13 setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
14 };
15 mql.addEventListener("change", onChange);
16 setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
17 return () => mql.removeEventListener("change", onChange);
18 }, []);
19​
20 return !!isMobile;