Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

Stream an LLM object into React, field by field — in one hook

Description and use

In React, streaming a JSON object from an LLM updates the UI field by field without parse errors and supports React 18 concurrency.

Problem

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.

Outcome

The hook allows React to render LLM-generated structured data progressively, avoiding parse errors, ensuring concurrent-safe updates, and providing clear field completion status.

Workflow

  • 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.

Evidence

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.

Source

data is a DeepPartial<Profile> that updates on every chunk — never throws.

Source

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.

Source

  • Record date: 2026-10-08T18:10:56.703Z