import { useReducer } from 'react'; import debounce from 'lodash/debounce'; function windowSizeReducer(state, action) { if (action.type === 'resize') { return action.width; } return state; } function useWindowSize() { const [width, dispatch] = useReducer(windowSizeReducer, window.innerWidth); useEffect( () => { function handleResize() { dispatch({ type: 'resize', width: window.innerWidth }); } const lazilyHandleResize = debounce(handleResize, 100); window.addEventListener('resize', lazilyHandleResize); return function detachResizeHandler() { window.removeEventListener('resize', lazilyHandleResize); }; }, [dispatch], ); return width; }