Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Hook to detect if a scrollable element reached the end.
function useScrollBottom<T extends HTMLElement>(offset?: number) {
const [atBottom, setAtBottom] = useState(false);
const scrollEl = useRef<T>(null);
useEffect(() => {
const { current } = scrollEl;
if (current) {
// by default we take the clientHeight into account, so "bottom" begins as soon as the last
// visible piece appears in the scrollable area
const withOffset = offset === undefined ? current.clientHeight : offset;
const handleScroll = () => {
if (
current.scrollTop + current.clientHeight + withOffset >=
current.scrollHeight
) {
setAtBottom(true);
} else {
setAtBottom(false);
}
};
current.addEventListener('scroll', handleScroll);
return () => current.removeEventListener('scroll', handleScroll);
}
}, [scrollEl.current, offset]);
return [scrollEl, atBottom] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.