Skip to content

Instantly share code, notes, and snippets.

@Izhaki
Last active June 27, 2021 22:24
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 Izhaki/ea32f4d3813a27bd4e9d137aff7a71c1 to your computer and use it in GitHub Desktop.
Save Izhaki/ea32f4d3813a27bd4e9d137aff7a71c1 to your computer and use it in GitHub Desktop.
React useAutoScrollToBottom.ts
import React from 'react';
export default function useAutoScrollToBottom(deps) {
const paused = React.useRef(false);
const element = React.useRef<HTMLDivElement | null>(null);
const onWheel = React.useCallback(() => {
const { scrollTop, scrollHeight, offsetHeight } = element.current || {
scrollTop: 0,
scrollHeight: 0,
offsetHeight: 0,
};
paused.current = scrollHeight - (scrollTop + offsetHeight) > 4;
}, []);
const ref = React.useCallback(
(el) => {
if (el) {
element.current = el;
el.addEventListener('wheel', onWheel, { passive: true });
} else if (element.current !== null) {
element.current.removeEventListener('wheel', onWheel);
element.current = null;
}
},
[onWheel]
);
React.useLayoutEffect(() => {
if (element.current && !paused.current) {
element.current.scrollTop = element.current.scrollHeight;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return { ref };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment