Last active
July 15, 2019 22:40
-
-
Save koistya/9d96f376b24e427cc976f311ece9f86f to your computer and use it in GitHub Desktop.
useScrollY() and useInnerWidth(nodeRef) React hooks
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 React from 'react'; | |
import { useScrollY, useInnerWidth } from './hooks'; | |
function Example(props) { | |
const nodeRef = React.useRef(); | |
const scrollY = useScrollY(); | |
const innerWidth = useInnerWidth(nodeRef); | |
return ( | |
<pre ref={nodeRef} {...props}> | |
scrollY: {scrollY} | |
innerWidth: {innerWidth} | |
</pre> | |
); | |
} | |
export default Example; |
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 debounce from 'lodash/debounce'; | |
import React from 'react'; | |
export function useScrollY() { | |
const [scrollY, setScrollY] = React.useState(0); | |
React.useEffect(() => { | |
function handleScroll() { | |
() => { | |
setScrollY(window.pageYOffset); | |
}, | |
166 /* Corresponds to 10 frames at 60 Hz */, | |
{ | |
maxWait: 322, | |
}, | |
} | |
window.addEventListener('scroll', handleScroll); | |
return () => { | |
window.removeEventListener('scroll', handleScroll); | |
}; | |
}, []); | |
return scrollY; | |
} | |
export function useInnerWidth(nodeRef) { | |
const [width, setWidth] = React.useState(null); | |
React.useEffect(() => { | |
const handleResize = debounce(() => { | |
const style = window.getComputedStyle(nodeRef.current, null); | |
setWidth( | |
nodeRef.current.clientWidth - | |
parseFloat(style.getPropertyValue('padding-left')) - | |
parseFloat(style.getPropertyValue('padding-right')), | |
); | |
}, 166 /* Corresponds to 10 frames at 60 Hz */); | |
handleResize(); | |
window.addEventListener('resize', handleResize); | |
return () => { | |
handleResize.cancel(); | |
window.removeEventListener('resize', handleResize); | |
}; | |
}, []); | |
return width; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment