Skip to main content
Prerequisites
The useStream() React hook provides a seamless way to integrate LangGraph into your React applications. It handles all the complexities of streaming, state management, and branching logic, letting you focus on building great chat experiences. Key features:
  • Messages streaming: Handle a stream of message chunks to form a complete message
  • Automatic state management for messages, interrupts, loading states, and errors
  • Conversation branching: Create alternate conversation paths from any point in the chat history
  • UI-agnostic design: bring your own components and styling
Let’s explore how to use useStream() in your React application. The useStream() provides a solid foundation for creating bespoke chat experiences. For pre-built chat components and interfaces, we also recommend checking out CopilotKit and assistant-ui.

Installation

Example

Customizing Your UI

The useStream() hook takes care of all the complex state management behind the scenes, providing you with simple interfaces to build your UI. Here’s what you get out of the box:
  • Thread state management
  • Loading and error states
  • Interrupts
  • Message handling and updates
  • Branching support
Here are some examples on how to use these features effectively:

Loading States

The isLoading property tells you when a stream is active, enabling you to:
  • Show a loading indicator
  • Disable input fields during processing
  • Display a cancel button

Resume a stream after page refresh

The useStream() hook can automatically resume an ongoing run upon mounting by setting reconnectOnMount: true. This is useful for continuing a stream after a page refresh, ensuring no messages and events generated during the downtime are lost.
By default the ID of the created run is stored in window.sessionStorage, which can be swapped by passing a custom storage in reconnectOnMount instead. The storage is used to persist the in-flight run ID for a thread (under lg:stream:${threadId} key).
You can also manually manage the resuming process by using the run callbacks to persist the run metadata and the joinStream function to resume the stream. Make sure to pass streamResumable: true when creating the run; otherwise some events might be lost.

Thread Management

Keep track of conversations with built-in thread management. You can access the current thread ID and get notified when new threads are created:
We recommend storing the threadId in your URL’s query parameters to let users resume conversations after page refreshes.

Messages Handling

The useStream() hook will keep track of the message chunks received from the server and concatenate them together to form a complete message. The completed message chunks can be retrieved via the messages property. By default, the messagesKey is set to messages, where it will append the new messages chunks to values["messages"]. If you store messages in a different key, you can change the value of messagesKey.
Under the hood, the useStream() hook will use the streamMode: "messages-tuple" to receive a stream of messages (i.e. individual LLM tokens) from any LangChain chat model invocations inside your graph nodes. Learn more about messages streaming in the streaming guide.

Interrupts

The useStream() hook exposes the interrupt property, which will be filled with the last interrupt from the thread. You can use interrupts to:
  • Render a confirmation UI before executing a node
  • Wait for human input, allowing agent to ask the user with clarifying questions
Learn more about interrupts in the How to handle interrupts guide.

Branching

For each message, you can use getMessagesMetadata() to get the first checkpoint from which the message has been first seen. You can then create a new run from the checkpoint preceding the first seen checkpoint to create a new branch in a thread. A branch can be created in following ways:
  1. Edit a previous user message.
  2. Request a regeneration of a previous assistant message.
For advanced use cases you can use the experimental_branchTree property to get the tree representation of the thread, which can be used to render branching controls for non-message based graphs.

Optimistic Updates

You can optimistically update the client state before performing a network request to the agent, allowing you to provide immediate feedback to the user, such as showing the user message immediately before the agent has seen the request.

Cached Thread Display

Use the initialValues option to display cached thread data immediately while the history is being loaded from the server. This improves user experience by showing cached data instantly when navigating to existing threads.

Optimistic Thread Creation

Use the threadId option in submit function to enable optimistic UI patterns where you need to know the thread ID before the thread is actually created.

TypeScript

The useStream() hook is friendly for apps written in TypeScript and you can specify types for the state to get better type safety and IDE support.
You can also optionally specify types for different scenarios, such as:
  • ConfigurableType: Type for the config.configurable property (default: Record<string, unknown>)
  • InterruptType: Type for the interrupt value - i.e. contents of interrupt(...) function (default: unknown)
  • CustomEventType: Type for the custom events (default: unknown)
  • UpdateType: Type for the submit function (default: Partial<State>)
If you’re using LangGraph.js, you can also reuse your graph’s annotation types. However, make sure to only import the types of the annotation schema in order to avoid importing the entire LangGraph.js runtime (i.e. via import type { ... } directive).

Event Handling

The useStream() hook provides several callback options to help you respond to different events:
  • onError: Called when an error occurs.
  • onFinish: Called when the stream is finished.
  • onUpdateEvent: Called when an update event is received.
  • onCustomEvent: Called when a custom event is received. See the streaming guide to learn how to stream custom events.
  • onMetadataEvent: Called when a metadata event is received, which contains the Run ID and Thread ID.

Learn More


Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.