diff --git a/packages/gatsby-theme-carbon/src/util/hooks/useScrollPosition.js b/packages/gatsby-theme-carbon/src/util/hooks/useScrollPosition.js index d5339a6f7..98125af7a 100644 --- a/packages/gatsby-theme-carbon/src/util/hooks/useScrollPosition.js +++ b/packages/gatsby-theme-carbon/src/util/hooks/useScrollPosition.js @@ -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', @@ -53,7 +47,7 @@ const useScrollPosition = options => { handleScroll.cancel(); window.removeEventListener('scroll', handleScroll); }; - }, [_options.throttle]); + }, []); return position; }; diff --git a/packages/gatsby-theme-carbon/src/util/hooks/useWindowSize.js b/packages/gatsby-theme-carbon/src/util/hooks/useWindowSize.js index 85428bae1..f7e20b2cb 100644 --- a/packages/gatsby-theme-carbon/src/util/hooks/useWindowSize.js +++ b/packages/gatsby-theme-carbon/src/util/hooks/useWindowSize.js @@ -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; }