Stream an LLM object into React, field by field — in one hook
Описание и применение
В React потоковое получение JSON от LLM обновляет 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