Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/use-chat-nullish-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ai-sdk/react": patch
---

Treat nullish `useChat` IDs the same as omitted IDs so the chat instance is not recreated on every render.
4 changes: 3 additions & 1 deletion packages/react/src/use-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ export function useChat<UI_MESSAGE extends UIMessage = UIMessage>({

const shouldRecreateChat =
('chat' in options && options.chat !== chatRef.current) ||
('id' in options && chatRef.current.id !== options.id);
('id' in options &&
options.id != null &&
chatRef.current.id !== options.id);

if (shouldRecreateChat) {
chatRef.current = 'chat' in options ? options.chat : new Chat(options);
Expand Down
76 changes: 76 additions & 0 deletions packages/react/src/use-chat.ui.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2216,6 +2216,82 @@ describe('id changes', () => {
});
});

describe('undefined id', () => {
setupTestComponent(
() => {
const [renderCount, setRenderCount] = React.useState(0);
const {
messages,
setMessages,
id: idKey,
} = useChat({
id: undefined,
generateId: mockId(),
});

return (
<div>
<div data-testid="id">{idKey}</div>
<div data-testid="render-count">{renderCount}</div>
<div data-testid="messages">{JSON.stringify(messages, null, 2)}</div>
<button
data-testid="set-message"
onClick={() => {
setMessages([
{
id: 'message-0',
role: 'user',
parts: [{ text: 'hi', type: 'text' }],
},
]);
}}
/>
<button
data-testid="rerender"
onClick={() => {
setRenderCount(count => count + 1);
}}
/>
</div>
);
},
{
init: TestComponent => <TestComponent />,
},
);

it('should not recreate chat when id is explicitly undefined', async () => {
const initialId = screen.getByTestId('id').textContent;

await userEvent.click(screen.getByTestId('set-message'));

await waitFor(() => {
expect(
JSON.parse(screen.getByTestId('messages').textContent ?? ''),
).toStrictEqual([
{
id: 'message-0',
role: 'user',
parts: [{ text: 'hi', type: 'text' }],
},
]);
});

await userEvent.click(screen.getByTestId('rerender'));

expect(screen.getByTestId('id').textContent).toBe(initialId);
expect(
JSON.parse(screen.getByTestId('messages').textContent ?? ''),
).toStrictEqual([
{
id: 'message-0',
role: 'user',
parts: [{ text: 'hi', type: 'text' }],
},
]);
});
});

describe('chat instance changes', () => {
setupTestComponent(
() => {
Expand Down