LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangGraph
  • Web
  • Channels
  • Pregel
  • Prebuilt
  • Remote
  • Stream
  • Overview
  • Getting started
  • useStream
  • Selectors
  • Interrupts & headless tools
  • Subagents & subgraphs
  • Fork & edit from a checkpoint
  • Submission queue
  • Multimodal media
  • Transports
  • Suspense
  • StreamProvider & context
  • Type safety
  • Migrating to v1
LangGraph SDK
  • Ui
  • Client
  • Auth
  • React
  • Logging
  • React Ui
  • Utils
  • Server
  • Stream
LangGraph Checkpoint
LangGraph Checkpoint MongoDB
LangGraph Checkpoint Postgres
  • Store
LangGraph Checkpoint Redis
  • Shallow
  • Store
LangGraph Checkpoint SQLite
LangGraph Checkpoint Validation
  • Cli
LangGraph API
LangGraph CLI
LangGraph CUA
  • Utils
LangGraph Supervisor
LangGraph Swarm
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangGraph
WebChannelsPregelPrebuiltRemoteStream
OverviewGetting starteduseStreamSelectorsInterrupts & headless toolsSubagents & subgraphsFork & edit from a checkpointSubmission queueMultimodal mediaTransportsSuspenseStreamProvider & contextType safetyMigrating to v1
LangGraph SDK
UiClientAuthReactLoggingReact UiUtilsServerStream
LangGraph Checkpoint
LangGraph Checkpoint MongoDB
LangGraph Checkpoint Postgres
Store
LangGraph Checkpoint Redis
ShallowStore
LangGraph Checkpoint SQLite
LangGraph Checkpoint Validation
Cli
LangGraph API
LangGraph CLI
LangGraph CUA
Utils
LangGraph Supervisor
LangGraph Swarm
Language
Theme
JavaScript@langchain/react

@langchain/react

Description

@langchain/react

React SDK for building AI-powered applications with Deep Agents, LangChain and LangGraph.

@langchain/react v1 ships a v2-native useStream hook together with a small family of companion selector hooks. The root hook gives you always-on access to thread state, messages, tool calls, and interrupts; the selector hooks open ref-counted subscriptions for the things that aren't needed on every view (per-subagent messages, media streams, submission queue, message metadata, raw channels, …).

Highlights

  • v2-native streaming protocol. Session-based transport with automatic re-attach on remount; no more reconnectOnMount / joinStream dance.
  • Selector-based subscriptions. Namespaced data (subagents, subgraphs, media) streams only when a component actually mounts the matching selector hook, and releases on unmount.
  • Always-on root projections. values, messages, toolCalls, and interrupts are live at the root with zero per-subscription cost.
  • Agent-brand type inference. useStream<typeof agent>() unwraps state, tool calls, and subagent state maps from an agent brand.
  • Discriminated options. The hosted Agent Server path and the custom-adapter path are two arms of a single typed union — mixing them is a compile-time error.
  • Multimodal media streams. Built-in assembly for audio, images, video, and files.
  • Suspense integration. useSuspenseStream hands the initial hydration phase to <Suspense> and non-streaming errors to Error Boundaries.

Installation

npm install @langchain/react @langchain/core

Peer dependencies: react (^18 || ^19), @langchain/core (^1.1.27).

Quick Start

import { useStream } from "@langchain/react";

function Chat() {
  const { messages, submit, isLoading } = useStream({
    assistantId: "agent",
    apiUrl: "http://localhost:2024",
  });

  return (
    <div>
      {messages.map((msg, i) => (
        <div key={msg.id ?? i}>{String(msg.content)}</div>
      ))}

      <button
        disabled={isLoading}
        onClick={() =>
          void submit({
            messages: [{ type: "human", content: "Hello!" }],
          })
        }
      >
        Send
      </button>
    </div>
  );
}

Mental model

@langchain/react v1 splits the surface into two layers:

  1. Root hook (useStream). Owns the thread lifecycle, the transport, and a handful of always-on projections (values, messages, toolCalls, interrupts, error, isLoading, discovery maps). Mount it once per thread.
  2. Companion selector hooks. Each one opens a ref-counted subscription when the first component mounts it and releases it when the last consumer unmounts. Use them for anything scoped to a namespace, a subagent / subgraph, a specific message, a specific extension channel, or a media stream.
import {
  useStream,
  useMessages,
  useToolCalls,
  useSubmissionQueue,
} from "@langchain/react";

function Chat() {
  const stream = useStream({ assistantId: "agent", apiUrl: "/api" });

  // Root: free reads, no new subscription.
  const messages = useMessages(stream); // same as stream.messages

  // Scoped: opens a namespaced subscription on mount.
  const queue = useSubmissionQueue(stream);
}

Documentation

Detailed guides live in ./docs. Start with the two files most apps need first:

  • useStream — options, return shape, submit(), stop(), respond(), hydrationPromise.
  • Companion selector hooks — useValues, useMessages, useToolCalls, useMessageMetadata, useChannel, useExtension, and friends.

Feature-specific guides:

  • Transports — SSE, WebSocket, HttpAgentServerAdapter, custom AgentServerAdapter.
  • Custom transports — implementing AgentServerAdapter against your own backend, with a worked walkthrough of examples/ui-react-transport.
  • Interrupts & headless tools — pausing runs, respond(), tools + onTool.
  • Fork / edit from a checkpoint — useMessageMetadata + submit({ forkFrom }).
  • Submission queue — multitaskStrategy: "enqueue" + useSubmissionQueue.
  • Subagents & subgraphs — discovery maps, scoped selector subscriptions.
  • Multimodal media — useAudio / useImages / useVideo / useFiles, useMediaURL, players.
  • useSuspenseStream — Suspense + Error Boundary integration.
  • StreamProvider / useStreamContext — share one stream across a subtree.
  • Type safety — agent-brand inference, prop-drilling, type helpers.

Migrating from v0 to v1

The useStream import name is unchanged, but the return shape, option bag, and protocol semantics all shifted. Most chat apps migrate in well under an hour — the full migration guide with line-by-line diffs lives in ./docs/v1-migration.md.

Legacy type aliases (UseStream, UseSuspenseStream, UseStreamOptions, UseStreamTransport, QueueEntry, GetToolCallsType, SubagentStream, …) and the legacy FetchStreamTransport class are no longer re-exported from @langchain/react. Apps still on the legacy surface can import directly from @langchain/langgraph-sdk/ui during their migration.

Playground

For complete end-to-end examples with full agentic UIs, visit the LangChain UI Playground.

License

MIT

Classes

Class

HttpAgentServerAdapter

Public v1 name for TransportAdapter plus optional high-level

Class

MediaAssemblyError

Typed error thrown through media.stream / rejected from

Functions

Function

applyHeadlessToolResumeCommand

Resume a headless-tool batch on the v1 commands transport.

Function

executeHeadlessTool

Function

filterOutHeadlessToolInterrupts

Strip headless-tool interrupts from a user-facing interrupt list.

Function

findHeadlessTool

Function

flushPendingHeadlessToolInterrupts

Execute and resume all newly seen headless-tool interrupts from a values

Function

handleHeadlessToolInterrupt

Function

headlessToolResumeCommand

Function

isHeadlessToolInterrupt

Function

parseHeadlessToolInterruptPayload

Parses a headless-tool interrupt value from the graph. Accepts both

Function

StreamProvider

Provides a shared useStream instance to all descendants via

Function

useAudio

Subscribe to a scoped audio-media stream. Returns an array of

Function

useAudioPlayer

Progressive audio playback for AudioMedia handles with a

Function

useChannel

Raw-events escape hatch. Subscribes to one or more channels at a

Function

useExtension

Subscribe to a custom:<name> stream extension — the most-recent

Function

useFiles

Subscribe to a scoped file-media stream. See useAudio for

Function

useImages

Subscribe to a scoped image-media stream. See useAudio for

Function

useMediaURL

Resolve the lazy MediaBase.objectURL promise into a string

Function

useMessageMetadata

Read metadata recorded for a specific message id — today exposes

Function

useMessages

Subscribe to a scoped messages stream. Pass stream and

Function

useProjection

React-side primitive that composes ChannelRegistry.acquire

Function

useStream

React binding for the v2-native stream runtime.

Function

useStreamContext

Accesses the shared stream instance from the nearest

Function

useSubmissionQueue

Function

useSuspenseStream

Function

useToolCalls

Subscribe to a scoped tools (tool-call) stream. Same target and

Function

useValues

Subscribe to a scoped values stream — most-recent state payload

Function

useVideo

Subscribe to a scoped video-media stream. See useAudio for

Function

useVideoPlayer

Bind a VideoMedia handle to a caller-owned <video> element.

Interfaces

Interface

AgentServerAdapter

Public v1 name for TransportAdapter plus optional high-level

Interface

AssembledToolCall

Reactive tool handle for framework bindings (stream.toolCalls,

Interface

AudioMedia

Shared surface across every media handle returned by

Interface

AudioPlayerHandle

Player controls + live state returned by useAudioPlayer.

Interface

FileMedia

Shared surface across every media handle returned by

Interface

FlushPendingHeadlessToolInterruptsOptions

Interface

HeadlessToolImplementation

Client-side implementation returned by headlessTool.implement(...).

Interface

HeadlessToolInterrupt

Represents a headless tool interrupt payload emitted by LangChain's

Interface

HttpAgentServerAdapterOptions

Interface

ImageMedia

Shared surface across every media handle returned by

Interface

MediaBase

Shared surface across every media handle returned by

Interface

MessageMetadata

Metadata tracked per message id. Surfaced to applications via

Interface

StreamStopOptions

Options for StreamController.stop / framework stop().

Interface

StreamSubmitOptions

Interface

SubagentDiscoverySnapshot

Lightweight discovery record for a subagent running inside the thread.

Interface

SubgraphDiscoverySnapshot

Lightweight discovery record for a subgraph running inside the thread.

Interface

SubmissionQueueEntry

Queued submission entry mirrored from the server-side run queue.

Interface

ToolEvent

Interface

UseAudioPlayerOptions

Options for useAudioPlayer.

Interface

UseStreamReturn

Interface

UseSubmissionQueueReturn

Reactive handle on the server-side submission queue.

Interface

UseVideoPlayerOptions

Options for useVideoPlayer.

Interface

VideoMedia

Shared surface across every media handle returned by

Interface

VideoPlayerHandle

Controls + live state returned by useVideoPlayer. Mirrors

Types

Type

AgentServerOptions

Type

AnyHeadlessToolImplementation

Type

AnyMediaHandle

Type

AnyStream

Erased stream handle useful as a parameter type for helpers and

Type

CustomAdapterOptions

Type

DefaultToolCall

Default tool call type when no specific tool definitions are provided.

Type

InferStateType

Unwrap the state shape from a compiled graph, a create-agent brand,

Type

InferSubagentStates

Infer the subagent → state map from a DeepAgent brand. Non-brands

Type

InferToolCalls

Infer the discriminated union of AssembledToolCall handles

Type

InferToolOutput

Infer the successful return type of a LangChain tool.

Type

MediaAssemblyErrorKind

Kinds of failure that can terminate a media handle prematurely.

Type

MediaBlockType

Block types this assembler knows how to reassemble into media handles.

Type

MessageMetadataMap

Read-only map exposed via MessageMetadataTracker.store.

Type

OnToolCallback

Type

PlayerStatus

Lifecycle state of an audio or video player returned by

Type

SelectorTarget

What a selector hook can be targeted at. Callers can pass any of:

Type

StreamProviderCustomProps

Props for StreamProvider when wiring a custom

Type

StreamProviderProps

Props for StreamProvider when talking to the default

Type

SubmissionQueueSnapshot

Read-only snapshot of the queue. The queue store hands this out

Type

ToolCallFromTool

Infer the streaming AssembledToolCall handle for a single

Type

ToolCallsFromTools

Infer a union of tool call types from an array of tools.

Type

ToolCallState

The lifecycle state of a tool call.

Type

ToolCallStatus

High-level outcome of a single tool call.

Type

ToolCallWithResult

Type

UseStreamOptions

Type

UseStreamResult

Convenience alias for the fully-resolved stream handle type.

Type

UseSuspenseStreamReturn

Return shape of useSuspenseStream. Identical to the

Type

WidenUpdateMessages

Widen an update type so its messages field also accepts