react-hooks

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

LiveKit React Hooks

LiveKit React Hooks

Build custom React UIs for realtime audio/video applications with LiveKit hooks.
使用LiveKit Hooks为实时音视频应用构建自定义React UI。

LiveKit MCP server tools

LiveKit MCP 服务器工具

This skill works alongside the LiveKit MCP server, which provides direct access to the latest LiveKit documentation, code examples, and changelogs. Use these tools when you need up-to-date information that may have changed since this skill was created.
Available MCP tools:
  • docs_search
    - Search the LiveKit docs site
  • get_pages
    - Fetch specific documentation pages by path
  • get_changelog
    - Get recent releases and updates for LiveKit packages
  • code_search
    - Search LiveKit repositories for code examples
  • get_python_agent_example
    - Browse 100+ Python agent examples
When to use MCP tools:
  • You need the latest API documentation or feature updates
  • You're looking for recent examples or code patterns
  • You want to check if a feature has been added in recent releases
  • The local references don't cover a specific topic
When to use local references:
  • You need quick access to core concepts covered in this skill
  • You're working offline or want faster access to common patterns
  • The information in the references is sufficient for your needs
Use MCP tools and local references together for the best experience.
该技能可与LiveKit MCP服务器配合使用,后者可直接获取最新的LiveKit文档、代码示例和更新日志。当你需要获取自本技能创建以来可能发生变化的最新信息时,可以使用这些工具。
可用的MCP工具:
  • docs_search
    - 搜索LiveKit文档站点
  • get_pages
    - 通过路径获取特定文档页面
  • get_changelog
    - 获取LiveKit软件包的近期版本发布和更新
  • code_search
    - 搜索LiveKit代码仓库中的代码示例
  • get_python_agent_example
    - 浏览100多个Python Agent示例
何时使用MCP工具:
  • 你需要最新的API文档或功能更新
  • 你正在寻找最新的示例或代码模式
  • 你想检查某个功能是否在近期版本中新增
  • 本地参考资料未涵盖特定主题
何时使用本地参考资料:
  • 你需要快速访问本技能涵盖的核心概念
  • 你处于离线状态,或希望快速获取常见模式
  • 参考资料中的信息已能满足你的需求
结合使用MCP工具和本地参考资料,以获得最佳体验。

Scope

适用范围

This skill covers hooks only from
@livekit/components-react
. These hooks provide low-level access to LiveKit room state, participants, tracks, and agent data for building fully custom UIs.
Important: For agent applications, do NOT use UI components from
@livekit/components-react
.
All UI components should come from the livekit-agents-ui skill, which provides shadcn-based components:
  • AgentSessionProvider
    - Session wrapper with audio rendering
  • AgentControlBar
    - Media controls
  • AgentAudioVisualizerBar/Grid/Radial
    - Audio visualizers
  • AgentChatTranscript
    - Chat display
  • And more
Use hooks from this skill only when you need custom behavior that the Agents UI components don't provide. The Agents UI components use these hooks internally.
本技能仅涵盖
@livekit/components-react
中的Hooks。这些Hooks提供对LiveKit房间状态、参与者、音视频轨道和Agent数据的底层访问,用于构建完全自定义的UI。
重要提示:对于Agent应用,请不要使用
@livekit/components-react
中的UI组件。
所有UI组件都应来自livekit-agents-ui技能,该技能提供基于shadcn的组件:
  • AgentSessionProvider
    - 带有音频渲染的会话包装器
  • AgentControlBar
    - 媒体控制栏
  • AgentAudioVisualizerBar/Grid/Radial
    - 音频可视化组件
  • AgentChatTranscript
    - 聊天记录展示组件
  • 以及更多组件
仅当你需要实现Agents UI组件未提供的自定义行为时,才使用本技能中的Hooks。Agents UI组件内部会使用这些Hooks。

References

参考资料

Consult these resources as needed:
  • ./references/livekit-overview.md -- LiveKit ecosystem overview and how these skills work together
  • ./references/participant-hooks.md -- Hooks for accessing participant data and state
  • ./references/track-hooks.md -- Hooks for working with audio/video tracks
  • ./references/room-hooks.md -- Hooks for room connection and state
  • ./references/session-hooks.md -- Hooks for managed agent sessions (useSession, useSessionMessages)
  • ./references/agent-hooks.md -- Hooks for voice AI agent integration
  • ./references/data-hooks.md -- Hooks for chat and data channels
根据需要查阅以下资源:
  • ./references/livekit-overview.md -- LiveKit生态系统概述以及这些技能如何协同工作
  • ./references/participant-hooks.md -- 用于访问参与者数据和状态的Hooks
  • ./references/track-hooks.md -- 用于处理音视频轨道的Hooks
  • ./references/room-hooks.md -- 用于房间连接和状态的Hooks
  • ./references/session-hooks.md -- 用于托管Agent会话的Hooks(useSession、useSessionMessages)
  • ./references/agent-hooks.md -- 用于语音AI Agent集成的Hooks
  • ./references/data-hooks.md -- 用于聊天和数据通道的Hooks

Installation

安装

bash
npm install @livekit/components-react livekit-client
bash
npm install @livekit/components-react livekit-client

Quick start

快速开始

Using hooks with AgentSessionProvider (standard approach)

使用Hooks搭配AgentSessionProvider(标准方式)

For agent apps, use
AgentSessionProvider
from the livekit-agents-ui skill for the session provider. The
useSession
hook from this package is required to create the session for
AgentSessionProvider
.
Required hook: Use
useSession
to create the session object:
tsx
import { useRef, useEffect } from 'react';
import { useSession } from '@livekit/components-react';
import { TokenSource, TokenSourceConfigurable } from 'livekit-client';
import { AgentSessionProvider } from '@/components/agents-ui/agent-session-provider';

function App() {
  const tokenSource: TokenSourceConfigurable = useRef(
    TokenSource.endpoint('/api/token')
  ).current;

  // Create session using useSession hook (required for AgentSessionProvider)
  const session = useSession(tokenSource, { agentName: 'your-agent' });

  useEffect(() => {
    session.start();
    return () => session.end();
  }, []);

  return (
    <AgentSessionProvider session={session}>
      <MyAgentUI />
    </AgentSessionProvider>
  );
}
Additional hook for agent state: Use
useVoiceAssistant
to access agent state, audio tracks, and transcriptions:
tsx
import { useVoiceAssistant } from '@livekit/components-react';

// This component must be inside an AgentSessionProvider
function CustomAgentStatus() {
  const { state, audioTrack, agentTranscriptions } = useVoiceAssistant();

  return (
    <div>
      <p>Agent state: {state}</p>
      {agentTranscriptions.map((t) => (
        <p key={t.id}>{t.text}</p>
      ))}
    </div>
  );
}
See the livekit-agents-ui skill for full component documentation.
对于Agent应用,请使用livekit-agents-ui技能中的
AgentSessionProvider
作为会话提供器。本包中的
useSession
Hook是为
AgentSessionProvider
创建会话所必需的。
必需的Hook:使用
useSession
创建会话对象:
tsx
import { useRef, useEffect } from 'react';
import { useSession } from '@livekit/components-react';
import { TokenSource, TokenSourceConfigurable } from 'livekit-client';
import { AgentSessionProvider } from '@/components/agents-ui/agent-session-provider';

function App() {
  const tokenSource: TokenSourceConfigurable = useRef(
    TokenSource.endpoint('/api/token')
  ).current;

  // 使用useSession Hook创建会话(AgentSessionProvider必需)
  const session = useSession(tokenSource, { agentName: 'your-agent' });

  useEffect(() => {
    session.start();
    return () => session.end();
  }, []);

  return (
    <AgentSessionProvider session={session}>
      <MyAgentUI />
    </AgentSessionProvider>
  );
}
用于Agent状态的额外Hook:使用
useVoiceAssistant
访问Agent状态、音视频轨道和转录内容:
tsx
import { useVoiceAssistant } from '@livekit/components-react';

// 该组件必须位于AgentSessionProvider内部
function CustomAgentStatus() {
  const { state, audioTrack, agentTranscriptions } = useVoiceAssistant();

  return (
    <div>
      <p>Agent状态: {state}</p>
      {agentTranscriptions.map((t) => (
        <p key={t.id}>{t.text}</p>
      ))}
    </div>
  );
}
查看livekit-agents-ui技能以获取完整的组件文档。

Custom microphone toggle

自定义麦克风开关

tsx
import { useTrackToggle } from '@livekit/components-react';
import { Track } from 'livekit-client';

// Use this inside an AgentSessionProvider for custom toggle behavior
function CustomMicrophoneButton() {
  const { enabled, toggle, pending } = useTrackToggle({
    source: Track.Source.Microphone,
  });

  return (
    <button onClick={() => toggle()} disabled={pending}>
      {enabled ? 'Mute' : 'Unmute'}
    </button>
  );
}
tsx
import { useTrackToggle } from '@livekit/components-react';
import { Track } from 'livekit-client';

// 在AgentSessionProvider内部使用,以实现自定义开关行为
function CustomMicrophoneButton() {
  const { enabled, toggle, pending } = useTrackToggle({
    source: Track.Source.Microphone,
  });

  return (
    <button onClick={() => toggle()} disabled={pending}>
      {enabled ? '静音' : '取消静音'}
    </button>
  );
}

Fully custom approach: useSession + SessionProvider (not recommended)

完全自定义方式:useSession + SessionProvider(不推荐)

Note: This pattern uses UI components from
@livekit/components-react
directly. For agent applications, use
AgentSessionProvider
from livekit-agents-ui instead, which wraps these components and provides a better developer experience.
For fully custom implementations without Agents UI components, you can use
useSession
with
SessionProvider
and
RoomAudioRenderer
directly. This gives you complete control but requires more manual setup.
Use this pattern only when you cannot use
AgentSessionProvider
from Agents UI:
tsx
import { useEffect, useRef } from 'react';
import { useSession, useAgent, SessionProvider, RoomAudioRenderer } from '@livekit/components-react';
import { TokenSource, TokenSourceConfigurable } from 'livekit-client';

function AgentApp() {
  // Use useRef to prevent recreating TokenSource on each render
  const tokenSource: TokenSourceConfigurable = useRef(
    TokenSource.sandboxTokenServer('your-sandbox-id')
  ).current;

  const session = useSession(tokenSource, {
    agentName: 'your-agent-name',
  });
  const agent = useAgent(session);

  // Auto-start session with cleanup
  useEffect(() => {
    session.start();
    return () => {
      session.end();
    };
  }, []);

  return (
    <SessionProvider session={session}>
      <RoomAudioRenderer />
      <div>
        <p>Connection: {session.connectionState}</p>
        <p>Agent: {agent.state}</p>
      </div>
    </SessionProvider>
  );
}
For production, use
TokenSource.endpoint()
instead of the sandbox:
tsx
const tokenSource: TokenSourceConfigurable = useRef(
  TokenSource.endpoint('/api/token')
).current;

const session = useSession(tokenSource, {
  roomName: 'my-room',
  participantIdentity: 'user-123',
  participantName: 'John',
  agentName: 'my-agent',
});
注意:该模式直接使用
@livekit/components-react
中的UI组件。对于Agent应用,请改用livekit-agents-ui中的
AgentSessionProvider
,它封装了这些组件并提供更好的开发体验。
如果不需要使用Agents UI组件,需要完全自定义实现,可以直接使用
useSession
搭配
SessionProvider
RoomAudioRenderer
。这能给你完全的控制权,但需要更多手动配置。
仅当无法使用Agents UI中的
AgentSessionProvider
时,才使用该模式:
tsx
import { useEffect, useRef } from 'react';
import { useSession, useAgent, SessionProvider, RoomAudioRenderer } from '@livekit/components-react';
import { TokenSource, TokenSourceConfigurable } from 'livekit-client';

function AgentApp() {
  // 使用useRef防止每次渲染时重新创建TokenSource
  const tokenSource: TokenSourceConfigurable = useRef(
    TokenSource.sandboxTokenServer('your-sandbox-id')
  ).current;

  const session = useSession(tokenSource, {
    agentName: 'your-agent-name',
  });
  const agent = useAgent(session);

  // 自动启动会话并清理
  useEffect(() => {
    session.start();
    return () => {
      session.end();
    };
  }, []);

  return (
    <SessionProvider session={session}>
      <RoomAudioRenderer />
      <div>
        <p>连接状态: {session.connectionState}</p>
        <p>Agent状态: {agent.state}</p>
      </div>
    </SessionProvider>
  );
}
生产环境中,请使用
TokenSource.endpoint()
而非沙箱环境:
tsx
const tokenSource: TokenSourceConfigurable = useRef(
  TokenSource.endpoint('/api/token')
).current;

const session = useSession(tokenSource, {
  roomName: 'my-room',
  participantIdentity: 'user-123',
  participantName: 'John',
  agentName: 'my-agent',
});

Hook categories

Hook分类

Participant hooks

参与者Hooks

Access participant data and state:
  • useParticipants()
    - All participants (local + remote)
  • useLocalParticipant()
    - Local participant with media state
  • useRemoteParticipants()
    - All remote participants
  • useRemoteParticipant(identity)
    - Specific remote participant
  • useParticipantInfo()
    - Identity, name, metadata
  • useParticipantAttributes()
    - Participant attributes
访问参与者数据和状态:
  • useParticipants()
    - 所有参与者(本地+远端)
  • useLocalParticipant()
    - 带有媒体状态的本地参与者
  • useRemoteParticipants()
    - 所有远端参与者
  • useRemoteParticipant(identity)
    - 指定的远端参与者
  • useParticipantInfo()
    - 身份标识、名称、元数据
  • useParticipantAttributes()
    - 参与者属性

Track hooks

音视频轨道Hooks

Work with audio/video tracks:
  • useTracks(sources)
    - Array of track references
  • useParticipantTracks(sources, identity)
    - Tracks for specific participant
  • useTrackToggle({ source })
    - Toggle mic/camera/screen
  • useIsMuted(trackRef)
    - Check if track is muted
  • useIsSpeaking(participant)
    - Check if participant is speaking
  • useTrackVolume(track)
    - Audio volume level
处理音视频轨道:
  • useTracks(sources)
    - 音视频轨道引用数组
  • useParticipantTracks(sources, identity)
    - 指定参与者的音视频轨道
  • useTrackToggle({ source })
    - 切换麦克风/摄像头/屏幕共享
  • useIsMuted(trackRef)
    - 检查音视频轨道是否静音
  • useIsSpeaking(participant)
    - 检查参与者是否在说话
  • useTrackVolume(track)
    - 音频音量级别

Room hooks

房间Hooks

Room connection and state:
  • useConnectionState()
    - Room connection state
  • useRoomInfo()
    - Room name and metadata
  • useLiveKitRoom(props)
    - Create and manage room instance
  • useIsRecording()
    - Check if room is being recorded
  • useMediaDeviceSelect({ kind })
    - Select audio/video devices
房间连接和状态:
  • useConnectionState()
    - 房间连接状态
  • useRoomInfo()
    - 房间名称和元数据
  • useLiveKitRoom(props)
    - 创建并管理房间实例
  • useIsRecording()
    - 检查房间是否正在录制
  • useMediaDeviceSelect({ kind })
    - 选择音视频设备

Session hooks (beta)

会话Hooks(测试版)

For session management (required for
AgentSessionProvider
):
  • useSession(tokenSource, options)
    - Create and manage agent session with connection lifecycle. Required for
    AgentSessionProvider
    .
  • useSessionMessages(session)
    - Combined chat and transcription messages
用于会话管理(
AgentSessionProvider
必需):
  • useSession(tokenSource, options)
    - 创建并管理带有连接生命周期的Agent会话。
    AgentSessionProvider
    必需。
  • useSessionMessages(session)
    - 合并的聊天和转录消息

Agent hooks (beta)

Agent Hooks(测试版)

Voice AI agent integration:
  • useVoiceAssistant()
    - Primary hook for agent state, tracks, and transcriptions. Works inside
    AgentSessionProvider
    .
  • useAgent(session)
    - Full agent state with lifecycle helpers. Requires session from
    useSession
    .
语音AI Agent集成:
  • useVoiceAssistant()
    - 用于访问Agent状态、音视频轨道和转录内容的主要Hook。需在
    AgentSessionProvider
    内部使用。
  • useAgent(session)
    - 带有生命周期助手的完整Agent状态。需要来自
    useSession
    的会话。

Data hooks

数据Hooks

Chat and data channels:
  • useChat()
    - Send/receive chat messages
  • useDataChannel(topic)
    - Low-level data messaging
  • useTextStream(topic)
    - Subscribe to text streams (beta)
  • useTranscriptions()
    - Get transcription data (beta)
  • useEvents(instance, event, handler)
    - Subscribe to typed events from session/agent
聊天和数据通道:
  • useChat()
    - 发送/接收聊天消息
  • useDataChannel(topic)
    - 底层数据消息传递
  • useTextStream(topic)
    - 订阅文本流(测试版)
  • useTranscriptions()
    - 获取转录数据(测试版)
  • useEvents(instance, event, handler)
    - 订阅会话/Agent的类型化事件

Context requirement

上下文要求

Most hooks require a room context. For agent applications, there are two approaches:
大多数Hooks需要房间上下文。对于Agent应用,有两种方式:

Option 1: useSession + AgentSessionProvider (standard)

方式1:useSession + AgentSessionProvider(标准方式)

Use
useSession
to create a session, then pass it to
AgentSessionProvider
from livekit-agents-ui. The
AgentSessionProvider
wraps
SessionProvider
and includes
RoomAudioRenderer
for audio playback. Hooks like
useVoiceAssistant
,
useTrackToggle
,
useChat
, and others work automatically inside this provider.
tsx
import { useRef, useEffect } from 'react';
import { useSession, useVoiceAssistant } from '@livekit/components-react';
import { TokenSource, TokenSourceConfigurable } from 'livekit-client';
import { AgentSessionProvider } from '@/components/agents-ui/agent-session-provider';

function App() {
  const tokenSource: TokenSourceConfigurable = useRef(
    TokenSource.endpoint('/api/token')
  ).current;

  // Create session using useSession hook (required)
  const session = useSession(tokenSource, { agentName: 'your-agent' });

  useEffect(() => {
    session.start();
    return () => session.end();
  }, []);

  return (
    <AgentSessionProvider session={session}>
      {/* Hooks from @livekit/components-react work here */}
      <MyAgentComponent />
    </AgentSessionProvider>
  );
}

function MyAgentComponent() {
  // useVoiceAssistant works inside AgentSessionProvider
  const { state, audioTrack } = useVoiceAssistant();
  return <div>Agent: {state}</div>;
}
使用
useSession
创建会话,然后将其传递给livekit-agents-ui中的
AgentSessionProvider
AgentSessionProvider
封装了
SessionProvider
并包含用于音频播放的
RoomAudioRenderer
useVoiceAssistant
useTrackToggle
useChat
等Hooks在该提供器内部可自动工作。
tsx
import { useRef, useEffect } from 'react';
import { useSession, useVoiceAssistant } from '@livekit/components-react';
import { TokenSource, TokenSourceConfigurable } from 'livekit-client';
import { AgentSessionProvider } from '@/components/agents-ui/agent-session-provider';

function App() {
  const tokenSource: TokenSourceConfigurable = useRef(
    TokenSource.endpoint('/api/token')
  ).current;

  // 使用useSession Hook创建会话(必需)
  const session = useSession(tokenSource, { agentName: 'your-agent' });

  useEffect(() => {
    session.start();
    return () => session.end();
  }, []);

  return (
    <AgentSessionProvider session={session}>
      {/* @livekit/components-react中的Hooks可在此处使用 */}
      <MyAgentComponent />
    </AgentSessionProvider>
  );
}

function MyAgentComponent() {
  // useVoiceAssistant可在AgentSessionProvider内部工作
  const { state, audioTrack } = useVoiceAssistant();
  return <div>Agent状态: {state}</div>;
}

Option 2: useSession + SessionProvider (not recommended)

方式2:useSession + SessionProvider(不推荐)

Note: This pattern uses UI components from
@livekit/components-react
directly. For agent applications, use Option 1 with
AgentSessionProvider
from livekit-agents-ui instead.
Only use this pattern if you need full manual control without using Agents UI components. You must include
RoomAudioRenderer
manually.
tsx
import { useRef, useEffect } from 'react';
import { useSession, useAgent, SessionProvider, RoomAudioRenderer } from '@livekit/components-react';
import { TokenSource, TokenSourceConfigurable } from 'livekit-client';

function App() {
  const tokenSource: TokenSourceConfigurable = useRef(
    TokenSource.sandboxTokenServer('your-sandbox-id')
  ).current;

  const session = useSession(tokenSource, { agentName: 'your-agent' });
  const agent = useAgent(session); // Pass session explicitly when using useSession

  useEffect(() => {
    session.start();
    return () => session.end();
  }, []);

  return (
    <SessionProvider session={session}>
      <RoomAudioRenderer />
      <MyAgentComponent agent={agent} />
    </SessionProvider>
  );
}
注意:该模式直接使用
@livekit/components-react
中的UI组件。对于Agent应用,请改用方式1,使用livekit-agents-ui中的
AgentSessionProvider
仅当你需要完全手动控制且不使用Agents UI组件时,才使用该模式。你必须手动包含
RoomAudioRenderer
tsx
import { useRef, useEffect } from 'react';
import { useSession, useAgent, SessionProvider, RoomAudioRenderer } from '@livekit/components-react';
import { TokenSource, TokenSourceConfigurable } from 'livekit-client';

function App() {
  const tokenSource: TokenSourceConfigurable = useRef(
    TokenSource.sandboxTokenServer('your-sandbox-id')
  ).current;

  const session = useSession(tokenSource, { agentName: 'your-agent' });
  const agent = useAgent(session); // 使用useSession时需显式传递会话

  useEffect(() => {
    session.start();
    return () => session.end();
  }, []);

  return (
    <SessionProvider session={session}>
      <RoomAudioRenderer />
      <MyAgentComponent agent={agent} />
    </SessionProvider>
  );
}

Best practices

最佳实践

General

通用原则

  1. Use Agents UI for standard UIs - For most agent applications, use the pre-built components from livekit-agents-ui. Use these hooks only when you need custom behavior.
  2. Optimize with updateOnlyOn - Many hooks accept
    updateOnlyOn
    to limit re-renders to specific events.
  3. Handle connection states - Always check
    useConnectionState()
    before accessing room data.
  4. Memoize TokenSource - Always use
    useRef
    when creating a
    TokenSource
    to prevent recreation on each render.
  1. 使用Agents UI构建标准UI - 对于大多数Agent应用,使用livekit-agents-ui中的预构建组件。仅当需要自定义行为时,才使用本技能中的Hooks。
  2. 使用updateOnlyOn优化性能 - 许多Hooks支持
    updateOnlyOn
    参数,可将重渲染限制为特定事件。
  3. 处理连接状态 - 在访问房间数据之前,始终检查
    useConnectionState()
    的返回值。
  4. 缓存TokenSource - 创建
    TokenSource
    时,始终使用
    useRef
    ,以防止每次渲染时重新创建。

For agent applications

针对Agent应用

  1. Use useSession with AgentSessionProvider - For most agent apps, create a session with
    useSession
    and pass it to
    AgentSessionProvider
    from livekit-agents-ui. The
    AgentSessionProvider
    handles audio rendering automatically.
  2. Use useVoiceAssistant for agent state - Inside
    AgentSessionProvider
    , use
    useVoiceAssistant
    to access agent state and transcriptions. This is simpler than
    useAgent
    .
tsx
import { useVoiceAssistant } from '@livekit/components-react';

function AgentDisplay() {
  const { state, audioTrack, agentTranscriptions } = useVoiceAssistant();
  // state: "disconnected" | "connecting" | "initializing" | "listening" | "thinking" | "speaking"
}
  1. Handle agent states properly - When using
    useAgent
    , handle all states including
    'idle'
    ,
    'pre-connect-buffering'
    , and
    'failed'
    :
tsx
const agent = useAgent(session);

if (agent.state === 'failed') {
  console.error('Agent failed:', agent.failureReasons);
}

if (agent.isPending) {
  // Show loading state
}
  1. Always use AgentSessionProvider - Use
    useSession
    +
    AgentSessionProvider
    from livekit-agents-ui for all agent applications. This is the standard and recommended approach.
  1. 搭配使用useSession与AgentSessionProvider - 对于大多数Agent应用,使用
    useSession
    创建会话,并将其传递给livekit-agents-ui中的
    AgentSessionProvider
    AgentSessionProvider
    会自动处理音频渲染。
  2. 使用useVoiceAssistant访问Agent状态 - 在
    AgentSessionProvider
    内部,使用
    useVoiceAssistant
    访问Agent状态和转录内容。这比
    useAgent
    更简单。
tsx
import { useVoiceAssistant } from '@livekit/components-react';

function AgentDisplay() {
  const { state, audioTrack, agentTranscriptions } = useVoiceAssistant();
  // state: "disconnected" | "connecting" | "initializing" | "listening" | "thinking" | "speaking"
}
  1. 正确处理Agent状态 - 使用
    useAgent
    时,需处理所有状态,包括
    'idle'
    'pre-connect-buffering'
    'failed'
tsx
const agent = useAgent(session);

if (agent.state === 'failed') {
  console.error('Agent启动失败:', agent.failureReasons);
}

if (agent.isPending) {
  // 显示加载状态
}
  1. 始终使用AgentSessionProvider - 对于所有Agent应用,使用
    useSession
    + livekit-agents-ui中的
    AgentSessionProvider
    。这是标准且推荐的方式。

Performance

性能优化

  1. Use LiveKit's built-in hooks for media controls - For track toggling, device selection, and similar features, use the provided hooks (
    useTrackToggle
    ,
    useMediaDeviceSelect
    ) rather than implementing your own. These hooks handle complex state management and have been rigorously tested.
  2. Subscribe to events with useEvents - Instead of manually managing event listeners, use
    useEvents
    to subscribe to session and agent events with proper cleanup:
tsx
useEvents(agent, AgentEvent.StateChanged, (state) => {
  console.log('Agent state:', state);
});
  1. 使用LiveKit内置Hooks处理媒体控制 - 对于轨道切换、设备选择等功能,使用提供的Hooks(
    useTrackToggle
    useMediaDeviceSelect
    )而非自行实现。这些Hooks可处理复杂的状态管理,且经过严格测试。
  2. 使用useEvents订阅事件 - 不要手动管理事件监听器,使用
    useEvents
    订阅会话和Agent事件,并自动清理:
tsx
useEvents(agent, AgentEvent.StateChanged, (state) => {
  console.log('Agent状态:', state);
});

Beta hooks

测试版Hooks

Several hooks in
@livekit/components-react
are marked as beta and may change:
  • useSession
    ,
    useSessionMessages
  • useAgent
    ,
    useVoiceAssistant
  • useTextStream
    ,
    useTranscriptions
Check the LiveKit components changelog for updates to these hooks.
@livekit/components-react
中的部分Hooks标记为测试版,可能会发生变化:
  • useSession
    ,
    useSessionMessages
  • useAgent
    ,
    useVoiceAssistant
  • useTextStream
    ,
    useTranscriptions
查看LiveKit组件更新日志以获取这些Hooks的更新信息。