Skip to content

Commit 83bfb3e

Browse files
author
Dylan Huang
committed
Refactor auto-scroll logic in ChatInterface to enhance user experience
- Replaced initial mount reference with a previous messages length reference to prevent scrolling on the first render and only scroll when new messages are added. - Improved scrolling behavior to avoid unnecessary scrolls when messages are removed, ensuring a smoother chat interaction.
1 parent eeed6b4 commit 83bfb3e

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

vite-app/src/components/ChatInterface.tsx

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,31 @@ export const ChatInterface = ({ messages }: ChatInterfaceProps) => {
1919
const scrollContainerRef = useRef<HTMLDivElement>(null);
2020
const resizeHandleRef = useRef<HTMLDivElement>(null);
2121
const heightResizeHandleRef = useRef<HTMLDivElement>(null);
22-
const isInitialMountRef = useRef(true);
22+
const prevMessagesLengthRef = useRef(0);
2323

2424
// Auto-scroll to bottom when new messages come in
2525
useEffect(() => {
26-
// Skip scrolling on initial mount
27-
if (isInitialMountRef.current) {
28-
isInitialMountRef.current = false;
26+
// On first render, just set the initial length without scrolling
27+
if (prevMessagesLengthRef.current === 0) {
28+
prevMessagesLengthRef.current = messages.length;
2929
return;
3030
}
3131

32-
// Scroll to bottom when messages change (after initial mount)
33-
if (messages.length > 0 && scrollContainerRef.current) {
34-
scrollContainerRef.current.scrollTo({
35-
top: scrollContainerRef.current.scrollHeight,
36-
behavior: "smooth",
37-
});
32+
// Only scroll if we have messages and the number of messages has increased
33+
// This prevents scrolling on initial mount or when messages are removed
34+
if (
35+
messages.length > 0 &&
36+
messages.length > prevMessagesLengthRef.current
37+
) {
38+
if (scrollContainerRef.current) {
39+
scrollContainerRef.current.scrollTo({
40+
top: scrollContainerRef.current.scrollHeight,
41+
behavior: "smooth",
42+
});
43+
}
3844
}
45+
// Update the previous length for the next comparison
46+
prevMessagesLengthRef.current = messages.length;
3947
}, [messages]);
4048

4149
// Handle horizontal resizing

0 commit comments

Comments
 (0)