The usePresence hook manages the current user's presence in a chat room. By default, it automatically enters presence on mount and leaves on unmount. Use usePresenceListener to observe the presence state of all users.
1
2
3
4
5
6
7
8
9
10
11
12
import { usePresence } from '@ably/chat/react';
const MyComponent = () => {
const { update, myPresenceState } = usePresence();
return (
<div>
<p>Present: {myPresenceState.present ? 'Yes' : 'No'}</p>
<button onClick={() => update({ status: 'away' })}>Set Away</button>
</div>
);
};This hook must be used within a ChatRoomProvider.
Parameters
The usePresence hook accepts an optional configuration object:
autoEnterLeaveoptionalBooleanleave() is invoked, automatic entry is disabled until enter or update is called. Default: true.initialDataoptionalPresenceDataupdate or enter for post-entry data changes.Returns
The usePresence hook returns an object with the following properties:
enterenter()leaveleave()updateupdate()myPresenceStateMyPresenceStateroomStatusRoomStatusroomErrorErrorInfo or UndefinedconnectionStatusConnectionStatusconnectionErrorErrorInfo or UndefinedEnter presence
enter(data?: PresenceData): Promise<void>Enters the current user into the chat room presence set. This notifies other users that you have joined the room.
Parameters
dataoptionalPresenceDataReturns
Promise<void>
Returns a promise. The promise is fulfilled when the user has successfully entered the presence set, or rejected with an ErrorInfo object.
Update presence data
update(data?: PresenceData): Promise<void>Updates the presence data for the current user in the chat room. Use this to change your status or other presence information without leaving and re-entering. Automatically enters if not already present.
Parameters
dataoptionalPresenceDataReturns
Promise<void>
Returns a promise. The promise is fulfilled when the presence data has been updated, or rejected with an ErrorInfo object.
Leave presence
leave(data?: PresenceData): Promise<void>Removes the current user from the chat room presence set. This notifies other users that you have left the room. If autoEnterLeave is true, calling leave() prevents automatic re-entry until enter or update is called.
Parameters
dataoptionalPresenceDataReturns
Promise<void>
Returns a promise. The promise is fulfilled when the user has left the presence set, or rejected with an ErrorInfo object.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { usePresence } from '@ably/chat/react';
function PresenceControls() {
const { enter, leave, update, myPresenceState } = usePresence({
initialData: { status: 'online', nickname: 'Alice' },
});
return (
<div>
<p>Status: {myPresenceState.present ? 'Online' : 'Offline'}</p>
{myPresenceState.error && <p>Error: {myPresenceState.error.message}</p>}
<button onClick={() => update({ status: 'away' })}>Set Away</button>
<button onClick={() => leave()}>Leave</button>
<button onClick={() => enter({ status: 'online' })}>Rejoin</button>
</div>
);
}