Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement