Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 11 additions & 12 deletions hooks/use-mobile.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import * as React from "react"

const MOBILE_BREAKPOINT = 768
const MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`

export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
function subscribe(onChange: () => void) {
const mql = window.matchMedia(MOBILE_QUERY)
mql.addEventListener("change", onChange)
return () => mql.removeEventListener("change", onChange)
}

React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
function getSnapshot() {
return window.matchMedia(MOBILE_QUERY).matches
}

return !!isMobile
export function useIsMobile() {
return React.useSyncExternalStore(subscribe, getSnapshot, () => false)
}
Loading