Skip to content

Commit

Permalink
fix: throttle windowSize for performance improvements on resize
Browse files Browse the repository at this point in the history
  • Loading branch information
vpicone committed May 21, 2019
1 parent 3394c4d commit b9af9ca
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
6 changes: 5 additions & 1 deletion packages/gatsby-theme-carbon/src/components/Header/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ const Header = ({ children, shouldHideHeader }) => {
<HeaderMenuButton
className="bx--header__action--menu"
aria-label="Open menu"
onClick={() => toggleNavState('leftNavIsOpen')}
onClick={() => {
toggleNavState('leftNavIsOpen');
toggleNavState('switcherIsOpen', 'close');
}}
isActive={leftNavIsOpen}
/>
<HeaderName prefix="" to="/" element={Link}>
Expand All @@ -54,6 +57,7 @@ const Header = ({ children, shouldHideHeader }) => {
onClick={() => {
toggleNavState('switcherIsOpen');
toggleNavState('searchIsOpen', 'close');
toggleNavState('leftNavIsOpen', 'close');
}}
>
{switcherIsOpen ? <Close20 /> : <AppSwitcher20 />}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import mediaqueries from '../../util/media-queries';

const responsiveStyles = {
width: '100%',
//padding: '0 1rem',
[mediaqueries.md]: {
width: '75%',
},
Expand Down
9 changes: 5 additions & 4 deletions packages/gatsby-theme-carbon/src/util/hooks/useWindowSize.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
import { throttle as _throttle } from 'lodash';

const initialValue = {
innerWidth: null,
Expand All @@ -10,28 +11,28 @@ const initialValue = {
function useWindowSize() {
const [windowSize, setWindowSize] = useState(initialValue);

function fetchWindowDimensionsAndSave() {
const fetchWindowDimensionsAndSave = _throttle(() => {
setWindowSize({
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
outerHeight: window.outerHeight,
outerWidth: window.outerWidth,
});
}
}, 100);

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

// set resize handler once on mount and clean before unmount
useEffect(() => {
window.addEventListener('resize', fetchWindowDimensionsAndSave);
return () => {
window.removeEventListener('resize', fetchWindowDimensionsAndSave);
};
}, []);
}, [fetchWindowDimensionsAndSave]);

return windowSize;
}
Expand Down

0 comments on commit b9af9ca

Please sign in to comment.