Skip to content

Instantly share code, notes, and snippets.

@sandeshdamkondwar
Forked from viclafouch/use-viewport.js
Created June 17, 2020 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandeshdamkondwar/78474d5656a00fe165dd8072b06661a2 to your computer and use it in GitHub Desktop.
Save sandeshdamkondwar/78474d5656a00fe165dd8072b06661a2 to your computer and use it in GitHub Desktop.
A custom React Hook for tracking the window width and to get the current viewport.
// hooks/use-viewport.js
import { useState, useEffect } from 'react'
export const MOBILE = 'MOBILE'
export const TABLET = 'TABLET'
export const DESKTOP = 'DESKTOP'
const getDevice = width => {
if (width < 768) return MOBILE
else if (width < 992) return TABLET
else return DESKTOP
}
export function useViewport() {
const [viewport, setViewport] = useState({
width: window.innerWidth,
device: getDevice(window.innerWidth)
})
useEffect(() => {
const handleResize = () =>
setViewport({
width: window.innerWidth,
device: getDevice(window.innerWidth)
})
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
}
}, [])
return { viewport }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment