Skip to content

Commit

Permalink
fix: event handler logic
Browse files Browse the repository at this point in the history
  • Loading branch information
vpicone committed May 22, 2019
1 parent 173288d commit adccb57
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 29 deletions.
12 changes: 3 additions & 9 deletions packages/gatsby-theme-carbon/src/util/hooks/useScrollPosition.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,13 @@ const getPosition = () => {
};
};

const defaultOptions = {
throttle: 100,
};

const useScrollPosition = options => {
const _options = { ...defaultOptions, ...options };

const useScrollPosition = () => {
const [position, setPosition] = useState(getPosition());

useEffect(() => {
const handleScroll = _throttle(() => {
setPosition(getPosition());
}, _options.throttle);
}, 100);

window.addEventListener(
'scroll',
Expand All @@ -53,7 +47,7 @@ const useScrollPosition = options => {
handleScroll.cancel();
window.removeEventListener('scroll', handleScroll);
};
}, [_options.throttle]);
}, []);

return position;
};
Expand Down
45 changes: 25 additions & 20 deletions packages/gatsby-theme-carbon/src/util/hooks/useWindowSize.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,43 @@
import { useState, useEffect } from 'react';
import { throttle as _throttle } from 'lodash';

const initialValue = {
innerWidth: null,
innerHeight: null,
outerWidth: null,
outerHeight: null,
};

function useWindowSize() {
const [windowSize, setWindowSize] = useState(initialValue);

const fetchWindowDimensionsAndSave = _throttle(() => {
setWindowSize({
const getWindowSize = () => {
if (typeof window !== 'undefined') {
return {
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
outerHeight: window.outerHeight,
outerWidth: window.outerWidth,
});
}, 100);
};
}
return {
innerWidth: null,
innerHeight: null,
outerWidth: null,
outerHeight: null,
};
};

function useWindowSize() {
const [windowSize, setWindowSize] = useState(getWindowSize());

// run on mount
useEffect(() => {
// run only once
fetchWindowDimensionsAndSave();
}, [fetchWindowDimensionsAndSave]);
setWindowSize(getWindowSize());
}, []);

// set resize handler once on mount and clean before unmount
useEffect(() => {
window.addEventListener('resize', fetchWindowDimensionsAndSave);
const handleResize = _throttle(() => {
setWindowSize(getWindowSize());
}, 300);
window.addEventListener('resize', handleResize);

return () => {
window.removeEventListener('resize', fetchWindowDimensionsAndSave);
handleResize.cancel();
window.removeEventListener('resize', handleResize);
};
}, [fetchWindowDimensionsAndSave]);
}, []);

return windowSize;
}
Expand Down

0 comments on commit adccb57

Please sign in to comment.