UNPKG

use-view-width

Version:

React Hook for returning the width of the viewport.

24 lines (17 loc) 574 B
import { useEffect, useState, useCallback } from 'react' const useViewWidth = () => { const [ viewWidth, setViewWidth ] = useState(() => { if (typeof window === 'undefined') return return window.innerWidth }) const handleWindowResize = useCallback(event => { setViewWidth(event.currentTarget.innerWidth) }, []) useEffect(() => { if (typeof window === 'undefined') return window.addEventListener('resize', handleWindowResize) return () => window.removeEventListener('resize', handleWindowResize) }, []) return viewWidth } export default useViewWidth