Room Context Setup

While the LiveKitRoom component has historically been used as the root of LiveKit applications, we recommend using the RoomContext.Provider directly for more control over room lifecycle and state management. This approach gives you more flexibility while still providing the necessary context for LiveKit components.

import * as React from 'react';
import { RoomContext } from '@livekit/components-react';
import { Room } from 'livekit-client';
const MyLiveKitApp = () => {
const [room] = useState(() => new Room({}));
// You can manage room connection lifecycle here
useEffect(() => {
room.connect('your-server-url', 'your-token');
return () => {
room.disconnect();
};
}, [room]);
return (
<RoomContext.Provider value={room}>
{/* Your components go here */}
</RoomContext.Provider>
);
};

This pattern offers several advantages:

  1. Direct control over Room instantiation and configuration
  2. Explicit connection lifecycle management
  3. Ability to handle connection states and errors more granularly
  4. Better integration with application state management

All LiveKit components that previously worked with LiveKitRoom will work identically with this setup, as they rely on the RoomContext being available in the component tree.

Was this page helpful?