Skip to content

Instantly share code, notes, and snippets.

@yongdamsh
Last active August 30, 2020 13:33
Show Gist options
  • Save yongdamsh/dba27de431d9b3a818cc4e4d65499796 to your computer and use it in GitHub Desktop.
Save yongdamsh/dba27de431d9b3a818cc4e4d65499796 to your computer and use it in GitHub Desktop.
React custom hook to subscribe resize event
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment