The useOccupancy hook provides realtime room occupancy information, automatically tracking the number of connections and presence members in a room.
React
1
2
3
4
5
6
import { useOccupancy } from '@ably/chat/react';
const MyComponent = () => {
const { connections, presenceMembers } = useOccupancy();
return <p>{connections} connections, {presenceMembers} present</p>;
};This hook must be used within a ChatRoomProvider.
Parameters
The useOccupancy hook accepts an optional configuration object:
listeneroptionalOccupancyListenerA callback invoked whenever an occupancy event is received. Removed when the component unmounts.
A callback to detect and respond to discontinuities.
A callback invoked when the room status changes. Removed when the component unmounts.
A callback invoked when the connection status changes. Removed when the component unmounts.
Returns
The useOccupancy hook returns an object with the following properties:
connectionsNumberThe current number of users connected to the room, kept up to date by the hook.
presenceMembersNumberThe current number of users present in the room, kept up to date by the hook.
roomStatusRoomStatusThe current status of the room, kept up to date by the hook.
roomErrorErrorInfo or UndefinedAn error object if the room is in an errored state.
connectionStatusConnectionStatusThe current connection status, kept up to date by the hook.
connectionErrorErrorInfo or UndefinedAn error object if there is a connection error.
Example
React
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { useOccupancy } from '@ably/chat/react';
function ViewerCount() {
const { connections, presenceMembers } = useOccupancy({
listener: (event) => {
console.log('Occupancy updated:', event.occupancy);
},
});
return (
<div>
<p>{connections} watching</p>
<p>{presenceMembers} in chat</p>
</div>
);
}