2021-09-03 05:11:21 -07:00
|
|
|
import { createContext, useContext, useEffect, useState } from 'react'
|
|
|
|
|
|
|
|
type ViewportContextProps = {
|
|
|
|
width: number
|
|
|
|
}
|
|
|
|
|
|
|
|
const ViewportContext = createContext({} as ViewportContextProps)
|
|
|
|
|
|
|
|
export const ViewportProvider = ({ children }) => {
|
|
|
|
const [mounted, setMounted] = useState(false)
|
2022-03-28 08:42:18 -07:00
|
|
|
const [width, setWidth] = useState<number>(0)
|
2021-09-03 05:11:21 -07:00
|
|
|
|
|
|
|
const handleWindowResize = () => {
|
2022-03-28 08:42:18 -07:00
|
|
|
if (typeof window !== 'undefined') {
|
|
|
|
setWidth(window.innerWidth)
|
|
|
|
}
|
2021-09-03 05:11:21 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
useEffect(() => {
|
2021-09-19 17:36:02 -07:00
|
|
|
handleWindowResize()
|
2021-09-03 05:11:21 -07:00
|
|
|
window.addEventListener('resize', handleWindowResize)
|
|
|
|
return () => window.removeEventListener('resize', handleWindowResize)
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
useEffect(() => setMounted(true), [])
|
|
|
|
if (!mounted) return null
|
|
|
|
|
|
|
|
return (
|
|
|
|
<ViewportContext.Provider value={{ width }}>
|
|
|
|
{children}
|
|
|
|
</ViewportContext.Provider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useViewport = () => {
|
|
|
|
const { width } = useContext(ViewportContext)
|
|
|
|
return { width }
|
|
|
|
}
|