mango-ui-v3/hooks/useViewport.tsx

39 lines
936 B
TypeScript
Raw Normal View History

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(() => {
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 }
}