mcpField
R
react-hooks

react-hooks

github.com/codestackr开发352 次安装41 周前更新
代码仓库

关于 react-hooks

此 Skill 使用 `@livekit/components-react` 的 hooks 构建实时音视频自定义界面,涵盖房间、参与者、媒体轨道、会话、Agent 和消息状态,并提供本地参考资料及查询最新 LiveKit 文档的指引。

主要功能

  1. 01房间与连接状态 hooks
  2. 02参与者和媒体轨道访问
  3. 03Agent 会话与语音状态 hooks
  4. 04聊天、数据通道和转录 hooks
  5. 05LiveKit MCP 文档工具使用指引

适用场景

  1. 01构建实时媒体房间的自定义控件
  2. 02显示 Agent 状态和转录内容
  3. 03为 LiveKit 界面添加聊天或数据通道

MCP 相关

配合 LiveKit MCP 服务使用;该服务提供文档搜索、页面获取、更新日志、代码搜索和 Python Agent 示例。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/codestackr/livekit-skills --skill react-hooks

安装后在 Claude Code 中输入/react-hooks确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
agent-hooks.md
data-hooks.md
livekit-overview.md
participant-hooks.md
room-hooks.md
session-hooks.md
track-hooks.md

详细介绍

LiveKit React Hooks

使用 LiveKit Hooks 为实时音视频应用构建自定义 React UI。

LiveKit MCP 服务工具

此技能与 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 工具和本地参考资料,可获得最佳体验。

范围

此技能仅涵盖 @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/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

安装

npm install @livekit/components-react livekit-client

快速入门

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

对于 Agent 应用,请使用 livekit-agents-ui 技能中的 AgentSessionProvider 作为会话提供程序。此软件包中的 useSession Hook 必须用于为 AgentSessionProvider 创建会话。

必需的 Hook:使用 useSession 创建会话对象:

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>
  );
}

用于获取 Agent 状态的附加 Hook:使用 useVoiceAssistant 访问 Agent 状态、音轨和转写文本:

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>
  );
}

完整的组件文档请参阅 livekit-agents-ui 技能。

自定义麦克风开关
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>
  );
}
完全自定义方案:使用 useSession + SessionProvider(不推荐)

注意:此模式直接使用 @livekit/components-react 中的 UI 组件。对于 Agent 应用,请改用 livekit-agents-ui 中的 AgentSessionProvider,它封装了这些组件,可提供更好的开发体验。

对于不使用 Agents UI 组件的完全自定义实现,可以直接将 useSession 与 SessionProvider 和 RoomAudioRenderer 搭配使用。这样可以完全掌控实现,但需要更多手动配置。

仅当无法使用 Agents UI 中的 AgentSessionProvider 时,才使用此模式:

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>
  );
}

对于生产环境,请使用 TokenSource.endpoint(),而不是沙盒:

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 类别

参与者 Hook

访问参与者数据和状态:

  • useParticipants() - 所有参与者(本地 + 远程)
  • useLocalParticipant() - 包含媒体状态的本地参与者
  • useRemoteParticipants() - 所有远程参与者
  • useRemoteParticipant(identity) - 指定的远程参与者
  • useParticipantInfo() - 身份、姓名、元数据
  • useParticipantAttributes() - 参与者属性
媒体轨道 Hook

处理音频/视频媒体轨道:

  • useTracks(sources) - 媒体轨道引用数组
  • useParticipantTracks(sources, identity) - 指定参与者的媒体轨道
  • useTrackToggle({ source }) - 切换麦克风/摄像头/屏幕
  • useIsMuted(trackRef) - 检查媒体轨道是否静音
  • useIsSpeaking(participant) - 检查参与者是否正在说话
  • useTrackVolume(track) - 音量级别
Room Hook

房间连接和状态:

  • useConnectionState() - 房间连接状态
  • useRoomInfo() - 房间名称和元数据
  • useLiveKitRoom(props) - 创建并管理房间实例
  • useIsRecording() - 检查房间是否正在录制
  • useMediaDeviceSelect({ kind }) - 选择音频/视频设备
Session Hook(测试版)

用于 Session 管理(AgentSessionProvider 必需):

  • useSession(tokenSource, options) - 创建并管理具有连接生命周期的 Agent Session。AgentSessionProvider 必需。
  • useSessionMessages(session) - 合并聊天和转录消息
Agent Hook(测试版)

语音 AI Agent 集成:

  • useVoiceAssistant() - 用于 Agent 状态、媒体轨道和转录内容的主要 Hook。可在 AgentSessionProvider 内使用。
  • useAgent(session) - 包含生命周期辅助工具的完整 Agent 状态。需要来自 useSession 的 Session。
数据 Hook

聊天和数据通道:

  • useChat() - 发送/接收聊天消息
  • useDataChannel(topic) - 低级数据消息传递
  • useTextStream(topic) - 订阅文本流(测试版)
  • useTranscriptions() - 获取转录数据(测试版)
  • useEvents(instance, event, handler) - 订阅来自 Session/Agent 的类型化事件

上下文要求

大多数 Hook 都需要房间上下文。对于 Agent 应用,有两种方案:

方案 1:useSession + AgentSessionProvider(标准)

使用 useSession 创建 Session,然后将其传递给 livekit-agents-ui 中的 AgentSessionProvider。AgentSessionProvider 封装了 SessionProvider,并包含用于音频播放的 RoomAudioRenderer。useVoiceAssistant、useTrackToggle、useChat 等 Hook 可在此 Provider 内自动使用。

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>;
}
方案 2:useSession + SessionProvider(不推荐)

注意:此模式直接使用 @livekit/components-react 中的 UI 组件。对于 Agent 应用,请改用方案 1,使用 livekit-agents-ui 中的 AgentSessionProvider。

仅当需要完全手动控制且不使用 Agents UI 组件时,才使用此模式。你必须手动添加 RoomAudioRenderer。

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>
  );
}

最佳实践

通用
  1. 标准 UI 使用 Agents UI - 对于大多数 Agent 应用,请使用 livekit-agents-ui 提供的预构建组件。只有在需要自定义行为时才使用这些钩子。
  2. 使用 updateOnlyOn 优化 - 许多钩子都接受 updateOnlyOn,可将重新渲染限制在特定事件上。
  3. 处理连接状态 - 访问房间数据前,请务必检查 useConnectionState()。
  4. 缓存 TokenSource - 创建 TokenSource 时,请务必使用 useRef,以防止每次渲染时都重新创建。
对于 Agent 应用
  1. 将 useSession 与 AgentSessionProvider 搭配使用 - 对于大多数 Agent 应用,请使用 useSession 创建会话,并将其传递给 livekit-agents-ui 中的 AgentSessionProvider。AgentSessionProvider 会自动处理音频渲染。

  2. 使用 useVoiceAssistant 获取 Agent 状态 - 在 AgentSessionProvider 内部,使用 useVoiceAssistant 访问 Agent 状态和转录内容。这比使用 useAgent 更简单。

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':
const agent = useAgent(session);

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

if (agent.isPending) {
  // Show loading state
}
  1. 始终使用 AgentSessionProvider - 对于所有 Agent 应用,请使用 livekit-agents-ui 中的 useSession + AgentSessionProvider。这是标准且推荐的方式。
性能
  1. 使用 LiveKit 内置钩子控制媒体 - 对于轨道切换、设备选择等功能,请使用提供的钩子(useTrackToggle、useMediaDeviceSelect),而不是自行实现。这些钩子可处理复杂的状态管理,并经过了严格测试。

  2. 使用 useEvents 订阅事件 - 不要手动管理事件侦听器,而应使用 useEvents 订阅会话和 Agent 事件,并确保正确清理:

useEvents(agent, AgentEvent.StateChanged, (state) => {
  console.log('Agent state:', state);
});
Beta 钩子

@livekit/components-react 中的多个钩子标记为 beta,可能会发生变化:

  • useSession、useSessionMessages
  • useAgent、useVoiceAssistant
  • useTextStream、useTranscriptions

请查看 LiveKit 组件更新日志,了解这些钩子的更新。

评论

支持 Markdown