Last active
August 30, 2020 13:33
-
-
Save yongdamsh/dba27de431d9b3a818cc4e4d65499796 to your computer and use it in GitHub Desktop.
React custom hook to subscribe resize event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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