Stream an LLM object into React, field by field — in one hook
说明与用途
在 React 中,流式获取 LLM 的 JSON 对象按字段更新 UI,避免解析错误并支持 React 18 并发。
问题
Parsing a streaming JSON response from an LLM in React causes errors and UI tearing because JSON.parse throws on partial chunks and React state updates are not concurrent-safe.
结果
The hook allows React to render LLM-generated structured data progressively, avoiding parse errors, ensuring concurrent-safe updates, and providing clear field completion status.
工作流
- 1. Define a Zod schema for the expected object.
- 2. Call useStreamingObject with the schema and a function that returns an SSE stream from the API.
- 3. Inside the hook, parse each chunk with trickle-json, coerce with coerce-json, and update state via useSyncExternalStore.
- 4. Render fields conditionally based on status flags and show a completion badge when done.
证据
JSON.parse throws until the very last token, you can't tell which fields are done, and if you're not careful you'll tear or leak the stream.
data is a DeepPartial<Profile> that updates on every chunk — never throws.
Under the hood it uses useSyncExternalStore, so renders are tearing-free and React-18 concurrent-safe, and the partial JSON parsing is handled by trickle-json.
- 记录日期: 2026-10-08T18:10:56.703Z