Optional
params: UsePresenceParamsAllows the registering of optional callbacks.
UsePresenceResponse - An object containing the Presence instance and methods to interact with it.
const MyComponent = () => {
const [userData, setUserData] = useState({ status: 'online' });
const params = useMemo(() => ({
enterWithData: userData,
leaveWithData: { reason: 'user_left' },
onConnectionStatusChange: (change) => console.log('Connection:', change.current),
onDiscontinuity: (error) => console.error('Discontinuity:', error)
}), [userData]);
const { presence, myPresenceState, update } = usePresence(params);
return <div>Present: {myPresenceState.present}</div>;
};
A hook that provides access to the Presence instance in the room. It will use the instance belonging to the room in the nearest ChatRoomProvider in the component tree. On calling, the hook will
enter
the room with the provided data andleave
the room when the component unmounts. The UsePresenceResponse.myPresenceState can be used to determine if the user is currently present in the room, and if any errors occurred while trying to enter or leave presence. Presence automatically attempts to re-enter the room after a network issue, but if it fails, it will emit an error with code91004
. You will need to remount the component, or call the Presence.update method exposed by this hook, to re-attempt entering presence again.Important: The
params
object should be memoized to prevent unnecessary re-renders. Passing a new object reference on each render will cause the hook's internal effects to re-run, potentially generating unnecessary messages to Ably and increasing costs.