1 "use client"
2
3 import React, {
4 createContext,
5 useCallback,
6 useContext,
7 useEffect,
8 useState,
9 } from "react"
10
11 export type MobileContextType = {
12 isMobile?: boolean
13 }
14
15 const MobileContext = createContext<MobileContextType | null>(null)
16
17 export type MobileProviderProps = {
18 children: React.ReactNode
19 }
20
21 export const MobileProvider = ({ children }: MobileProviderProps) => {
22 const [isMobile, setIsMobile] = useState(false)
23
24 const handleResize = useCallback(() => {
25 if (window.innerWidth < 1024 && !isMobile) {
26 setIsMobile(true)
27 } else if (window.innerWidth >= 1024 && isMobile) {
28 setIsMobile(false)
29 }
30 }, [isMobile])
31
32 useEffect(() => {
33 window.addEventListener("resize", handleResize)
34
35 return () => {
36 window.removeEventListener("resize", handleResize)
37 }
38 }, [handleResize])
39
40 useEffect(() => {
41 handleResize()
42 }, [])
43
44 return (
45 <MobileContext.Provider
46 value={{
47 isMobile,
48 }}
49 >
50 {children}
51 </MobileContext.Provider>
52 )
53 }
54
55 export const useMobile = () => {
56 const context = useContext(MobileContext)
57
58 if (!context) {
59 throw new Error("useMobile must be used within a MobileProvider")
60 }
61
62 return context
63 }