useOccupancy

Open in

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:

listeneroptionalOccupancyListener
A callback invoked whenever an occupancy event is received. Removed when the component unmounts.
onDiscontinuityoptionalDiscontinuityListener
A callback to detect and respond to discontinuities.
onRoomStatusChangeoptionalRoomStatusChange
A callback invoked when the room status changes. Removed when the component unmounts.
onConnectionStatusChangeoptionalConnectionStatusChange
A callback invoked when the connection status changes. Removed when the component unmounts.

Returns

The useOccupancy hook returns an object with the following properties:

connectionsNumber
The current number of users connected to the room, kept up to date by the hook.
presenceMembersNumber
The current number of users present in the room, kept up to date by the hook.
roomStatusRoomStatus
The current status of the room, kept up to date by the hook.
roomErrorErrorInfo or Undefined
An error object if the room is in an errored state.
connectionStatusConnectionStatus
The current connection status, kept up to date by the hook.
connectionErrorErrorInfo or Undefined
An 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>
  );
}