Branch

The Branch component manages multiple versions of AI messages, allowing users to navigate between different response branches. It provides a clean, modern interface with customizable themes and keyboard-accessible navigation buttons.

What are the key strategies for optimizing React performance?
Ha
Here's the first response to your question. This approach focuses on performance optimization.
AI

Installation

npx ai-elements@latest add branch

Usage

import {
Branch,
BranchMessages,
BranchNext,
BranchPage,
BranchPrevious,
BranchSelector,
} from '@/components/ai-elements/branch';
<Branch defaultBranch={0}>
<BranchMessages>
<Message from="user">
<MessageContent>Hello</MessageContent>
</Message>
<Message from="user">
<MessageContent>Hi!</MessageContent>
</Message>
</BranchMessages>
<BranchSelector from="user">
<BranchPrevious />
<BranchPage />
<BranchNext />
</BranchSelector>
</Branch>

Usage with AI SDK

Branching is an advanced use case that you can implement yourself to suit your application's needs. While the AI SDK does not provide built-in support for branching, you have full flexibility to design and manage multiple response paths as required.

Features

  • Context-based state management for multiple message branches
  • Navigation controls for moving between branches (previous/next)
  • Uses CSS to prevent re-rendering of branches when switching
  • Branch counter showing current position (e.g., "1 of 3")
  • Automatic branch tracking and synchronization
  • Callbacks for branch change and navigation using onBranchChange
  • Support for custom branch change callbacks
  • Responsive design with mobile-friendly controls
  • Clean, modern styling with customizable themes
  • Keyboard-accessible navigation buttons

Props

<Branch />

defaultBranch?:

number
The index of the branch to show by default (default: 0).

onBranchChange?:

(branchIndex: number) => void
Callback fired when the branch changes.

[...props]:

React.HTMLAttributes<HTMLDivElement>
Any other props are spread to the root div.

<BranchMessages />

[...props]:

React.HTMLAttributes<HTMLDivElement>
Any other props are spread to the root div.

<BranchSelector />

from:

UIMessage["role"]
Aligns the selector for user, assistant or system messages.

[...props]:

React.HTMLAttributes<HTMLDivElement>
Any other props are spread to the selector container.

<BranchPrevious />

[...props]:

React.ComponentProps<typeof Button>
Any other props are spread to the underlying shadcn/ui Button component.

<BranchNext />

[...props]:

React.ComponentProps<typeof Button>
Any other props are spread to the underlying shadcn/ui Button component.

<BranchPage />

[...props]:

React.HTMLAttributes<HTMLSpanElement>
Any other props are spread to the underlying span element.