How to Auto-Scroll a React Chat Log to the Newest Message
To scroll a chat list to the newest message, set the list element's scrollTop to its scrollHeight inside a useLayoutEffect. However, if you always scroll, someone reading earlier messages gets pulled back to the bottom. So I record whether the user was at the bottom at each scroll, and scroll only when they were. Messages that arrive while the user is reading earlier ones are announced with a "↓ N new" button.
I built a component called ChatLog and checked how it behaves when a message arrives, when the user has scrolled up, and when an image loads late. I also compared it with a version that calls scrollIntoView on the last element, and with a version that uses only the CSS flex-direction: column-reverse to pin the view to the bottom.
The test environment is Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transpiled them with esbuild, and operated Chromium with Playwright. Instead of communicating with a server, I called a function from the page to add messages. I reproduced mouse wheel operations with Playwright's mouse.wheel. I did not test touch operation on smartphones, screen reader announcements, Firefox, or Safari.

The cursor, operation counts, and operation labels in the GIF (wheel up and click, shown in Japanese) are overlays I added for the recording. The pink highlights on messages and buttons appear only at the moment a message arrives, when the count on the new-message button changes (the whole button is highlighted), and when the button is pressed (the pressed button and the last message of the destination).
- 1. Scroll to the end of the list only when the user is at the bottom
- 2. Decide whether you are at the bottom before the new message arrives
- 3. Don't move while the user is reading above, and show the count of new messages
- 4. Re-align to the bottom when images load later
- 5. With scrollIntoView, the whole page also scrolls
- 6. Pin to the bottom with CSS column-reverse alone
Scroll to the end of the list only when the user is at the bottom
Here is the whole component. It receives an array of messages as props and renders the list.
import { useLayoutEffect, useRef, useState } from 'react';
export type Message = { id: number; author: 'me' | 'cat'; text: string; image?: string };
// If the distance from the bottom edge is within this many px (40), treat it as being at the bottom
const THRESHOLD = 40;
export function ChatLog({ messages }: { messages: Message[] }) {
const listRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
// Whether the user was at the bottom at the last scroll
const atBottomRef = useRef(true);
const prevCountRef = useRef(messages.length);
const [unread, setUnread] = useState(0);
const scrollToBottom = () => {
const el = listRef.current;
if (el) el.scrollTop = el.scrollHeight;
};
const handleScroll = () => {
const el = listRef.current;
if (!el) return;
atBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight <= THRESHOLD;
if (atBottomRef.current) setUnread(0);
};
// When messages are added, scroll before the screen is painted
useLayoutEffect(() => {
const added = messages.length - prevCountRef.current;
prevCountRef.current = messages.length;
if (added <= 0) return;
const last = messages[messages.length - 1];
if (atBottomRef.current || last.author === 'me') {
scrollToBottom();
} else {
setUnread((n) => n + added);
}
}, [messages]);
// Also when the content height changes (e.g., images loading), keep the view at the bottom if the user was there
useLayoutEffect(() => {
const content = contentRef.current;
if (!content) return;
const observer = new ResizeObserver(() => {
if (atBottomRef.current) scrollToBottom();
});
observer.observe(content);
return () => observer.disconnect();
}, []);
return (
<div className="chat">
<div ref={listRef} className="chat-list" role="log" aria-label="メッセージ" onScroll={handleScroll}>
<div ref={contentRef}>
{messages.map((m) => (
<div key={m.id} className={`msg msg-${m.author}`}>
{m.text}
{m.image && <img src={m.image} alt="" />}
</div>
))}
</div>
</div>
{unread > 0 && (
<button type="button" className="new-badge" onClick={scrollToBottom}>
↓ 新着 {unread}件
</button>
)}
</div>
);
}
Give the list element a height and overflow-y: auto so that only the inside of the list scrolls. The new-message button is placed over the lower part of the list.
.chat { position: relative; width: 360px; }
.chat-list { height: 300px; overflow-y: auto; border: 1px solid #9aa5ab; border-radius: 8px; padding: 8px; box-sizing: border-box; background: #fff; }
.new-badge { position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%); padding: 6px 14px; border: none; border-radius: 16px; background: #067a98; color: #fff; font-size: 14px; cursor: pointer; }
Scrolling is done by putting scrollHeight (the height of the whole content) into scrollTop. scrollHeight is larger than the maximum scrollable amount by the visible height of the list (clientHeight). In the test environment, the scroll position stopped at the bottom and the remaining distance to the bottom was 0. To decide whether we are at the bottom, I use scrollHeight - clientHeight - scrollTop to get the remaining distance, as described in MDN's scrollHeight page. The MDN example checks whether the remaining distance is 1px or less. Here I allowed some margin and used 40px or less.
I perform the scroll inside useLayoutEffect because, as React's useLayoutEffect reference explains, it runs before the browser repaints the screen. This prevents the order where the state with the new message appended is painted first and the scroll happens afterward. I did not compare the visual difference from useEffect in this test.
I made the message list an element with role="log". According to MDN's log role page, an element with the log role is treated as aria-live="polite" even without specifying it, so screen readers read out changes inside it once the user's operation settles. In testing, I only confirmed that it appears in the accessibility tree as log "メッセージ".
The table below shows the result of receiving three messages from the other person while at the bottom, with 12 messages displayed in a 300px-tall list. "Remaining distance to bottom" is the value of scrollHeight - clientHeight - scrollTop.
| Operation | scrollTop | Remaining distance to bottom |
|---|---|---|
| Initial display | 228 | 0 |
| 1 message arrives | 270 | 0 |
| 2nd message arrives | 312 | 0 |
| 3rd message arrives | 354 | 0 |
The reason the list is already scrolled to the bottom at the initial display is ResizeObserver. At the initial display the number of messages has not increased, so the first useLayoutEffect does nothing. However, the Resize Observer spec says that a notification is delivered when observation starts. Since atBottomRef is true at first, that notification scrolls to the bottom.
Decide whether you are at the bottom before the new message arrives
ChatLog decides whether the user is at the bottom in handleScroll each time they scroll, and stores the result in a ref. When a message arrives, it only reads that ref and does not decide again.
You might think it should decide when the message arrives, but useLayoutEffect runs after the new message has been added to the list. The content has already grown by the added amount, so even a user who was at the bottom now has a remaining distance that has increased by the message's height. For comparison, I also tried this version:
useLayoutEffect(() => {
const el = listRef.current;
if (!el) return;
// Checks whether we are at the bottom after the new message has been added
if (el.scrollHeight - el.scrollTop - el.clientHeight <= 40) {
el.scrollTop = el.scrollHeight;
}
}, [messages]);
After scrolling the list to the bottom, I received a one-line message. The remaining distance became 42px, so it did not scroll. The height of a one-line message, including the gap to the previous message, was 42px, which is larger than the 40px threshold. Even if the threshold is widened, the same thing will happen when a longer message arrives.
The reason atBottomRef is a ref rather than state is that its value changes on every scroll but does not affect the display. As React's useRef reference explains, changing a ref's current does not trigger a re-render.
Don't move while the user is reading above, and show the count of new messages
When a message from the other person arrives while you are not at the bottom, the component does not scroll. Instead, it adds the number of arrived messages to unread. Only when unread is 1 or more does it show the "↓ N new" button. Pressing the button scrolls to the bottom. That scroll triggers handleScroll, which resets unread to 0, so the button disappears.
The table below shows the result after scrolling the list up by 200px and then receiving two messages from the other person.
| Operation | scrollTop | Remaining distance to bottom | New-message button |
|---|---|---|---|
| Scroll up 200px | 154 | 200 | None |
| 1 message arrives | 154 | 242 | ↓ 1 new |
| 2nd message arrives | 154 | 284 | ↓ 2 new |
| Press the button | 438 | 0 | None |
Even when messages arrived, scrollTop stayed at 154, and the message at the top of the visible list did not change. For comparison, I also tried a version that always scrolls to the bottom whenever the number of messages increases, regardless of position. After scrolling up 200px and receiving one message, scrollTop changed from 28 to 270, pulling the view back to the bottom.
Messages you send yourself always scroll to the bottom, even if you are reading earlier messages, so you can see what you sent. In ChatLog, when the last message's author is 'me', it scrolls regardless of whether you were at the bottom. After scrolling up 200px, I typed text into the input and sent it, and the remaining distance to the bottom became 0.
Re-align to the bottom when images load later
When a message contains an image, the image may not be loaded yet when the message arrives, and the height increases after it loads. With the approach that always scrolls to the bottom when messages increase, the view ends up off the bottom by the height of the image.
In the test, I returned a 200px-tall image after 500ms and received one message containing it.
| Approach | Remaining distance right after arrival | Remaining distance after the image loads |
|---|---|---|
| Always scroll to the bottom when messages increase | 0 | 200 |
ChatLog (also re-aligns with ResizeObserver) |
0 | 0 |
In ChatLog, a ResizeObserver watches the inner element that wraps the messages. When its height changes, it scrolls to the bottom again if the user was at the bottom. In the "always scroll" approach, scrollTop did not change even when the image loaded and the content grew. atBottomRef is changed only in handleScroll, which is called on scroll. If the scroll position does not change, handleScroll is not called, so atBottomRef stays true. That is why it can re-align to the bottom.
If you know the image size in advance, you can also specify width and height on the img element. According to MDN's img element page, when both are specified, the browser computes the aspect ratio before loading and reserves the space, which reduces layout shift after loading. I did not test this approach.
With scrollIntoView, the whole page also scrolls
Another approach is to place an empty element at the end of the list and call scrollIntoView() on it.
const endRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
endRef.current?.scrollIntoView();
}, [messages]);
// Place <div ref={endRef} /> at the end of the list
As MDN's scrollIntoView() page says, scrollIntoView() scrolls every scrollable ancestor of the element so that it becomes visible. Not only the list but the page itself is subject to scrolling.
I tested this on a page with 900px-tall separate content above and below the chat list. I scrolled the page to the top and received one message while the chat list was off-screen. Not only the list but the entire page scrolled, and window.scrollY changed from 0 to 1207. With the ChatLog approach, which changes the list's scrollTop, window.scrollY stayed at 0 on the same page.
MDN says that passing container: 'nearest' to scrollIntoView scrolls only the nearest scrollable ancestor. In Chromium 153 in the test environment, passing { block: 'end', container: 'nearest' } kept window.scrollY at 0. However, the type definitions in typescript 7.0.2 do not yet include container. Passing it directly caused a type error saying that container does not exist on ScrollIntoViewOptions. So for the movement test, I widened the type when passing the option. Also, because the target is the bottom edge of the empty element, the remaining distance to the bottom edge of the list was 7px.
Pin to the bottom with CSS column-reverse alone
If you set display: flex and flex-direction: column-reverse on the list, the scroll position starts at the bottom. Pass the array sorted newest first.
<div className="chat-list chat-reverse" role="log" aria-label="メッセージ">
{[...messages].reverse().map((m) => (
<div key={m.id} className={`msg msg-${m.author}`}>{m.text}</div>
))}
</div>
.chat-reverse { display: flex; flex-direction: column-reverse; }
In the test environment, without any JavaScript scrolling, the bottom was visible at the initial display and when a message arrived. At this time scrollTop is 0. Scrolling up 200px changes scrollTop to -200. When a message arrived in that state, it changed to -248, but the message at the top of the visible list was the same. MDN's scrollTop page also says that for elements using column-reverse, scrollTop is 0 at the bottom and becomes negative as you scroll up.
The code gets shorter, but the HTML order is the reverse of the displayed order. In the test, the first element in the list was the newest message. MDN's flex-direction page warns that when the visual order differs from the HTML order, people using screen readers may not be able to read in the correct order. The direction of the scrollTop values is also reversed, so the at-bottom check and the new-message button must be written to match that direction. If you are going to build the new-message button too, deciding the scroll position in JavaScript, as ChatLog does, avoids confusion about the direction of the values.





