Skip to content

Instantly share code, notes, and snippets.

@viclafouch
Last active June 17, 2020 19:17
Show Gist options
  • Save viclafouch/7a5423f1ab76b22c253d3ff7c0e2c500 to your computer and use it in GitHub Desktop.
Save viclafouch/7a5423f1ab76b22c253d3ff7c0e2c500 to your computer and use it in GitHub Desktop.

Revisions

  1. viclafouch revised this gist Jun 16, 2020. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions use-viewport.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    // hooks/use-viewport.js
    import { useState, useEffect } from 'react'

    export const MOBILE = 'MOBILE'
  2. viclafouch revised this gist Jun 16, 2020. No changes.
  3. viclafouch created this gist Jun 16, 2020.
    32 changes: 32 additions & 0 deletions use-viewport.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    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 }
    }