Don't re-render more than necessary with useIsMobile hook

This commit is contained in:
Marshall Polaris 2022-09-24 16:30:43 -07:00
parent ec57200b67
commit 2be2c07df5

View File

@ -1,7 +1,13 @@
import { useWindowSize } from 'web/hooks/use-window-size'
import { useEffect, useState } from 'react'
// matches talwind sm breakpoint
export function useIsMobile() {
const { width } = useWindowSize()
return (width ?? 0) < 640
const [isMobile, setIsMobile] = useState<boolean>()
useEffect(() => {
// matches tailwind sm breakpoint
const onResize = () => setIsMobile(window.innerWidth < 640)
onResize()
window.addEventListener('resize', onResize)
return () => window.removeEventListener('resize', onResize)
}, [])
return isMobile
}