I am trying to better understand how the room cont...
# ask-ai
r
I am trying to better understand how the room context work and how to communicate with the frontend. List me examples with custom frontend
t
Thanks for reaching out, Ivan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're exploring the room context in LiveKit! It acts as a shared space that makes real-time interactions smooth and enjoyable, supporting features like media sharing, event handling, and keeping everyone’s state in sync. To help you communicate between your frontend and backend, here are some friendly options you can try: • State Synchronization: You can share custom states easily using participant attributes or room metadata. • Remote Procedure Calls (RPC): This lets you define and call methods across your frontend and backend seamlessly. • Direct Data Messages: Feel free to send any kind of data using
room.sendData()
or
participant.publishData()
. To make things clearer, here’s a simple example of a custom React frontend you might find helpful:
Copy code
import { Room } from 'livekit-client';
import React, { useMemo, useEffect, createContext, useContext } from 'react';

const LiveKitContext = createContext<Room | null>(null);

export const useLiveKit = () => {
  const room = useContext(LiveKitContext);
  if (!room) throw new Error("useLiveKit must be used inside LiveKitProvider");
  return room;
};

export function LiveKitProvider({ children }: { children: React.ReactNode }) {
  const room = useMemo(() => new Room(), []);

  useEffect(() => {
    if (room.state === 'disconnected') {
      room.connect('wss://your-livekit-server', 'your-participant-token')
        .catch(err => console.error("Failed to connect", err));
    }

    room.on('dataReceived', (payload, participant) => {
      console.log('Data from', participant.identity, ':', payload.toString());
    });

    return () => {
      room.disconnect();
    };
  }, [room]);

  return (
    <LiveKitContext.Provider value={room}>
      {children}
    </LiveKitContext.Provider>
  );
}
This approach uses React context to share the
Room
instance and gracefully handle events like
dataReceived
. And remember, you can always send data back using
room.localParticipant.publishData()
. If you’d like to dive deeper or see more examples, I warmly recommend checking out the Web and mobile frontends documentation or exploring the Note-taking Assistant frontend. They’re great resources to guide you along the way! Sources: Agent Testing & CI/CD | livekit/livekit_composite | DeepWiki | lib/src/context/room_context.dart | Rooms, participants, and tracks | LiveKit docs | Connecting to LiveKit | LiveKit docs | Web and mobile frontends | LiveKit Docs