In React, how do I create a room instance from a r...
# ask-ai
h
In React, how do I create a room instance from a room's name?
t
Thanks for reaching out, tri.nguyen. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to create a room instance from a room's name in React using LiveKit, here’s a simple way to do it: 1. Initialize a Room instance: Just use
new Room()
to create a
Room
object. You can add options like
adaptiveStream
and
dynacast
to get the best video and audio quality. 2. Keep the instance in state: Use the
useState
hook to hold onto your
Room
instance even when your component re-renders:
const [roomInstance] = useState(() => new Room({ adaptiveStream: true, dynacast: true }));
3. Get an access token: Grab a token from your backend that includes the room name, participant identity, and permissions you need. 4. Connect to the room: Inside a
useEffect
hook, call
roomInstance.connect()
with your LiveKit server URL and the token:
await roomInstance.connect(process.env.NEXT_PUBLIC_LIVEKIT_URL, data.token);
5. Share the room context: Wrap your UI components with
RoomContext.Provider
so everything inside can access the room instance:
Copy code
<RoomContext.Provider value={roomInstance}>
  {/* LiveKit components */}
</RoomContext.Provider>
Oh, and if you want an even easier way, check out the
LiveKitRoom
component from
@livekit/components-react
. It handles room creation and connection for you. Here’s a quick example:
Copy code
<LiveKitRoom serverUrl={url} token={token} connect={true}>
  {children}
</LiveKitRoom>
Just so you know, rooms get created automatically the moment the first participant connects, and the room name is set through the access token. Sources: Next.js 12 quickstart | LiveKit Docs | Connecting to LiveKit | LiveKit Docs | src/components/LiveKitRoom.tsx | packages/react/src/components/LiveKitRoom.tsx | client/components/livekit/room.tsx
h
I create a dispatch to let LiveKit handle creating a room:
Copy code
async function createExplicitDispatch({
  apiKey,
  apiSecret,
  livekitUrl,
  phoneNumber,
}: {
  apiKey: string;
  apiSecret: string;
  livekitUrl: string;
  phoneNumber: string;
}) {
  const roomName = `room-${generateRandomString()}`;
  const agentName = 'outbound-caller';

  const agentDispatchClient = new AgentDispatchClient(livekitUrl, apiKey, apiSecret);

  const dispatch = await agentDispatchClient.createDispatch(roomName, agentName, {
    metadata: phoneNumber,
  });
  console.log('created dispatch', dispatch);

  return dispatch;
}
So I want to get the room instance that the dispatch creates.
t
Hey there! Just to make sure I’m on the right track—how would you like to get hold of the room instance created by the dispatch? Are you hoping to access it directly in your app’s code, or are you trying to check it out through some interface or tool? Let me know, and I’ll help you figure it out!
h
I wish to access it directly in my app's code