The props for the ChatRoomProvider component.
Props for the ChatRoomProvider component.
Optionalchildren?: ReactNode | ReactNode[]Children nodes.
The name of the room.
Optionaloptions?: RoomOptionsOverriding options to use when creating the room. See RoomOptions for details.
Important:
options should be memoized to prevent unnecessary room recreations. Passing a new object reference
on each render will cause the room to be released and recreated.const MyRoomComponent = () => {
const [typing, setTyping] = useState(true);
const roomOptions = useMemo(() => ({
typing: { timeoutMs: 5000 },
}), []); // Stable reference - options don't change
return (
<ChatRoomProvider name="my-room" options={roomOptions}>
<MyChat />
</ChatRoomProvider>
);
};
A React element that provides the room context to its children
An Ably.ErrorInfo with ReactHookMustBeUsedWithinProvider When used outside of a ChatRoomProvider
An Ably.ErrorInfo with RoomExistsWithDifferentOptions if room exists with different options
import * as Ably from 'ably';
import React, { useMemo } from 'react';
import { ChatClient } from '@ably/chat';
import {
ChatClientProvider,
ChatRoomProvider,
useMessages,
useRoom,
} from '@ably/chat/react';
const chatClient: ChatClient; // existing ChatClient instance
// Child component using room functionality
const ChatInterface = () => {
const { roomName } = useRoom();
const { sendMessage } = useMessages();
return (
<div>
<h2>Chat Room: {roomName}</h2>
<button onClick={() => sendMessage({ text: 'Hello!' })}>
Send Message
</button>
</div>
);
};
const BasicExample = () => {
return (
<ChatClientProvider client={chatClient}>
<ChatRoomProvider name="general-chat">
<ChatInterface />
</ChatRoomProvider>
</ChatClientProvider>
);
};
import { ChatClientProvider, ChatRoomProvider } from '@ably/chat/react';
import { ChatClient } from '@ably/chat';
const chatClient: ChatClient; // existing ChatClient instance
// Example with room options (properly memoized)
const CustomOptions = () => {
// Memoize options to prevent room recreation
const roomOptions = useMemo(() => ({
typing: {
timeoutMs: 10000 // 10 second typing timeout
},
}), []); // Empty dependency array = stable reference
return (
<ChatClientProvider client={chatClient}>
<ChatRoomProvider name="team-room" options={roomOptions}>
<ChatInterface />
</ChatRoomProvider>
</ChatClientProvider>
);
};
React Context Provider that makes a specific Room available to child components.
The provider automatically handles room attachment/detachment and provides the room instance to child components through room-specific hooks like useMessages, usePresence, useTyping, etc.
Multiple providers for the same room (with same options) share the same underlying room instance through reference counting, making it safe to have multiple components using the same room simultaneously.
When the first ChatRoomProvider for a room mounts, it creates and attaches the room. When the last provider unmounts, it releases the room.