Skip to content

Instantly share code, notes, and snippets.

@koistya
Last active July 15, 2019 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koistya/9d96f376b24e427cc976f311ece9f86f to your computer and use it in GitHub Desktop.
Save koistya/9d96f376b24e427cc976f311ece9f86f to your computer and use it in GitHub Desktop.
useScrollY() and useInnerWidth(nodeRef) React hooks
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;
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