Use Auto Scroll
Displays additional information on hover or focus.
Chat
- Welcome to the chat!
- Feel free to add new messages.
Features
- 🔄 Automatically scrolls to the newest item when new content is added
- 🛑 Pauses auto-scroll when the user scrolls up or interacts manually
- 🖱️ Handles wheel and touch events to accurately detect user intention
- 🔄 Continues auto-scroll once the user scrolls back to the bottom threshold
Installation
CLI
Manual
Copy and paste the following code into your project.
Update the import paths to match your project setup.
Usage
Import and use the hook or auto-scroll utility.
Or use the autoScrollListRef
directly in a component:
API / Parameters
useAutoScroll(enabled: boolean, deps: any[]): RefObject<HTMLUListElement>
- enabled:
boolean
— Iftrue
, auto-scroll is active. Iffalse
, no automatic scrolling occurs. - deps:
any[]
— Dependency array to re-run the hook effect (e.g.,[items]
or[messages]
), so auto-scroll logic can observe changes and scroll when new content is added. - Returns: A
RefObject<HTMLUListElement>
that should be attached to the<ul>
element you want to auto-scroll. Example:const listRef = useAutoScroll(true, [items]);
autoScrollListRef(list: HTMLUListElement): () => void
- list:
HTMLUListElement
— The actual DOM<ul>
element to observe and scroll. PasslistRef.current
inside auseEffect
. - Returns: A cleanup function that removes event listeners and disconnects the
MutationObserver
. Call this in the cleanup phase of youruseEffect
.
Behavior Details
- Automatic Pausing: When a user scrolls up (via mouse wheel or touch),
shouldAutoScroll
is set tofalse
. This prevents the list from jumping down while the user is reading earlier content. - Resuming Auto-Scroll: If the scroll position returns near the bottom threshold (within half the scroll height),
shouldAutoScroll
becomestrue
again. The next content addition will scroll the list to the bottom. - Cleanup: Always invoke the cleanup function returned by
autoScrollListRef
insideuseEffect
cleanup. Otherwise, event listeners and observers will persist after unmount. - Performance Considerations: The
MutationObserver
watches for new child nodes. In very high-frequency updates, consider throttling incoming updates or narrowing observation options to avoid excessive callbacks.
Notes
- Mobile / Touch Events: The hook listens for
touchstart
andtouchmove
to detect upward swipes and pause auto-scroll appropriately. This ensures better UX on touch devices. - CSS Classes: The examples use Tailwind classes (e.g.,
h-80 overflow-y-auto rounded-md
). You can adjust height, spacing, or border styles to fit your design. - Compatibility: Tested with React 18 and Next.js 14+ in TypeScript environments. Ensure your project has proper TS types for
useRef<HTMLUListElement>
.