useAutoScroll

A custom hook that automatically manages scrolling to the bottom of a container while respecting manual user navigation.

Note

The auto-scroll behavior is intelligently paused if the user manually scrolls up to read previous content. It will resume automatically once the user scrolls back within the threshold area.

Tip

This hook includes an image load listener. This ensures that if images are added to a chat (which change the scroll height as they load), the container will still correctly adjust its scroll position.

Installation

bash

Description

The useAutoScroll is designed for chat interfaces, logs, or feed-based UIs where content is added dynamically. It uses a MutationObserver to watch for DOM changes and automatically scrolls to the bottom if the user is already near the end (within a specified threshold). If the user scrolls up manually to read older content, the hook smartly pauses auto-scrolling to prevent interrupting their reading experience.

Parameters

NameTypeDescription
options.behavior'auto' | 'smooth'Defines the scrolling transition animation. Default 'auto'.
options.enabledbooleanInitial state of the auto-scroll functionality. Default: 'true'.
options.thresholdnumberDistance in pixels from the bottom to consider the user at the end. Default 100.

Return values

NameTypeDescription
autoScrollEnabledbooleanReactive state indicating if auto-scrolling is currently active.
disableAutoScroll() => voidFunction to manually turn off the auto-scrolling logic.
enableAutoScroll() => voidFunction to manually turn on auto-scrolling and immediately scroll to the bottom.
isAtBottombooleanReactive state indicating if the container is currently scrolled to the end.
refReact.RefObject<HTMLDivElement>The ref that must be attached to the scrollable container element.
scrollToBottom(forceSmooth?: boolean) => voidImperative function to scroll the container to the bottom.

Demo

Auto-scroll

Source code

tsx