Skip to Content
Runlane
RealtimeReact hooks

Streams in React

Use useRunStream to show text or data that a task writes while it runs.

useRunStream follows one named stream on one run. Your component re-renders as new parts arrive. Use it for AI answers, live logs, or any output that arrives in pieces.

Declare the stream on the task

A task declares each stream name and the type of its parts. Then it appends parts while it runs. This page uses the writeAnswer task from set up realtime. These are its stream parts:

src/tasks/write-answer.ts
export const writeAnswer = task({
  id: 'answer.write',
  // ...
  streams: { answer: z.string() },
  async run({ question }, context) {
    // ...
    await context.stream('answer').append(`Answer to: ${question}. Part ${i} of 10. `)
    // ...
  },
})

The server checks each part against the schema before it saves it. See stream run output to pipe a model's output or append in batches.

Show the stream

src/answer.tsx
'use client'

import { useRunStream } from '@runlane/react'

import type { writeAnswer } from './tasks/write-answer'

export function Answer({ runId }: { runId: string }) {
  const { parts, truncated, error } = useRunStream<typeof writeAnswer>(runId, 'answer')

  if (error) return <p>Could not load the answer.</p>
  return (
    <>
      {truncated && <p>Showing only the most recent parts.</p>}
      <pre>{parts.join('')}</pre>
    </>
  )
}
  • parts is an array of the retained parts. Here each part is a string.
  • The name 'answer' is checked against the task's streams. A typo is a type error.
  • If the connection drops, the hook picks up where it stopped. Parts are not repeated.
  • Saved parts arrive first. By default, the hook keeps the last 2,000 parts (contractDefaults.realtime.clientMaxParts); older parts are dropped and truncated becomes true.

The stream and the final output are separate. To show the task's return value, use useRun.

Retries and attempts

If a task fails and retries, the new attempt can write a different answer. Each attempt has its own parts.

By default, the hook shows only the newest attempt. When a new attempt starts, parts starts over. You never see two answers joined together.

To show every attempt, set mode to RunStreamMode.All and read attempts:

import { RunStreamMode, useRunStream } from '@runlane/react'

export function AnswerHistory({ runId }: { runId: string }) {
  const { attempts } = useRunStream<typeof writeAnswer>(runId, 'answer', {
    mode: RunStreamMode.All,
  })

  return attempts.map(({ attempt, parts, closeReason }) => (
    <section key={attempt}>
      <h3>
        Attempt {attempt}: {closeReason ?? 'writing'}
      </h3>
      <pre>{parts.join('')}</pre>
    </section>
  ))
}
Modeparts holdsattempts holds
RunStreamMode.Latest (default)The newest attempt's partsOnly the newest attempt
RunStreamMode.AllThe newest attempt's partsEvery attempt still in memory

closeReason is set when an attempt stops writing. It is one of completed, failed, released, cancelled, expired, or abandoned.

Long streams

The hook keeps at most maxParts parts in memory. The default is contractDefaults.realtime.clientMaxParts. When there are more, it drops the oldest parts and sets truncated to true.

import { contractDefaults } from '@runlane/contracts/realtime'

const { parts, truncated } = useRunStream<typeof writeAnswer>(runId, 'answer', {
  maxParts: contractDefaults.realtime.clientMaxParts * 2,
})

return (
  <>
    {truncated && <p>Showing the most recent part of the log.</p>}
    <pre>{parts.join('')}</pre>
  </>
)

maxParts must be a whole number from 1 to contractDefaults.realtime.clientMaxPartsLimit. It counts parts across all attempts kept in memory, and it also caps how many attempts are kept. The oldest go first.

Handle each part

onData runs once for every part, in order. Use it for side effects, such as sounds or counters, instead of rendering.

useRunStream<typeof writeAnswer>(runId, 'answer', {
  onData(part) {
    wordCount.current += part.split(' ').length
  },
})

Renders are grouped to save work. onData is not. It sees every part, even ones that maxParts later drops.

Tasks with several streams

When a task declares more than one stream, pass the stream name as a second type argument. This gives each stream its exact part type:

// chatReply declares streams: { answer: z.string(), tokens: z.number() }
const answer = useRunStream<typeof chatReply, 'answer'>(runId, 'answer') // parts: string[]
const tokens = useRunStream<typeof chatReply, 'tokens'>(runId, 'tokens') // parts: number[]

Without the second argument, parts uses a union of all part types, such as (string | number)[].

Options

useRunStream(runId, name, options?) takes the shared options plus:

OptionMeaning
modeRunStreamMode.Latest (default) or RunStreamMode.All
maxPartsMost parts to keep in memory. Defaults to contractDefaults.realtime.clientMaxParts.
onData(part)Called for every part, in order

It returns { parts, attempts, truncated, error, isConnected, stop }. See the React reference for exact types.

On this page