fix(react): prevent stale transport in useChat when React state changes #12330
+34
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Human View
Summary
Fixes #7819
The
transportoption (includingbody,headers) passed touseChatwas captured once when theChatinstance was created and never updated on subsequent renders. This causedtransport.bodyvalues referencing React state to always send the initial (stale) value, even when the state changed.Problem
Workarounds like passing
bodyas a function also didn't help because the entire transport was stale.Fix
Applied the same ref-based indirection pattern already used for callbacks (
onToolCall,onFinish,onData,onError,sendAutomaticallyWhen) to thetransportoption:transportRefis created and updated on every render with the latest transportChatinstance receives stable wrapper functions that always delegate totransportRef.currentsendMessagesorreconnectToStreamis called, it executes on the latest transport with freshbody/headersvaluesThis is a minimal, non-breaking change — only
packages/react/src/use-chat.tsis modified, following the existing pattern exactly.Verification
main)onToolCalletc.AI View (DCCE Protocol v1.0)
Metadata
AI Contribution Summary
Verification Steps Performed
Human Review Guidance
transport.body,transportRef.current,packages/react/src/use-chat.tsMade with M7 Cursor