LiveObjects React Hooks
Render shared state in React components that update for every user as soon as anyone changes it.
Build React interfaces where every user sees the same scores, settings or document state, updated in realtime as anyone changes it. A single hook reads the shared state on a channel as plain data, re-renders your component when that data changes, and gives you a handle to update it.
The useObject hook is part of the Ably Pub/Sub SDK's React support. It builds on the Pub/Sub React Hooks, using the client from the nearest PubSubClientProvider and the channel from the nearest ChannelProvider. It manages the LiveObjects lifecycle for you: it waits for the channel's state to synchronize, subscribes to changes when your component mounts, and unsubscribes when it unmounts.
The following component shows Alice's score and increments it for everyone on the channel. Game is the shape of the channel object, defined in Subscribe to the channel object:
1
2
3
4
5
6
7
8
import type { LiveMap, PathObject } from '@ably/pubsub-device/liveobjects';
import { useObject } from '@ably/pubsub-device/liveobjects/react';
const AliceScore = () => {
const { value, object } = useObject((obj: PathObject<LiveMap<Game>>) => obj.get('scores').get('alice'));
return <button onClick={() => object?.increment(1)}>Alice: {value ?? 0}</button>;
};Install
The @ably/pubsub-device package includes the useObject hook in its @ably/pubsub-device/liveobjects/react entry point. You don't need to install any additional packages.
npm install @ably/pubsub-deviceAuthenticate
Client code that runs in a browser authenticates with token authentication, which keeps your API key on your server. The examples on this page fetch tokens from an /auth endpoint on your server.
To read objects with useObject, the token needs the object-subscribe capability. To update objects, it also needs the object-publish capability.
Set up the providers
Create a client with the LiveObjects plugin and pass it to a PubSubClientProvider. Then wrap the components that use LiveObjects in a ChannelProvider that sets the LiveObjects channel modes:
OBJECT_SUBSCRIBEis required to read objects on the channel.OBJECT_PUBLISHis required to update objects on the channel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { createClient } from '@ably/pubsub-device';
import { LiveObjects } from '@ably/pubsub-device/liveobjects';
import { ChannelProvider, PubSubClientProvider } from '@ably/pubsub-device/react';
import { createRoot } from 'react-dom/client';
const container = document.getElementById('root')!;
const root = createRoot(container);
const pubsubDeviceClient = createClient({
authUrl: '/auth',
plugins: { LiveObjects },
});
root.render(
<PubSubClientProvider client={pubsubDeviceClient}>
<ChannelProvider channelName="cup-tea-pot" options={{ modes: ['OBJECT_SUBSCRIBE', 'OBJECT_PUBLISH'] }}>
<App />
</ChannelProvider>
</PubSubClientProvider>
);Subscribe to the channel object
Call useObject with no selector to subscribe to the whole channel object. The examples on this page use a channel object with the following shape, which they pass to the hook as a type:
1
2
3
4
5
6
7
8
9
import type { LiveCounter, LiveMap } from '@ably/pubsub-device/liveobjects';
type Game = {
title: string;
scores: LiveMap<{
alice: LiveCounter;
bob: LiveCounter;
}>;
};The hook returns value, a plain-data snapshot of the object, and object, the PathObject for it. value is the result of calling compact() on the object, so a LiveMap becomes a plain JavaScript object and a LiveCounter becomes a number.
object is undefined until the channel attaches and the channel object completes its initial synchronization, so check it and render a loading state until then. It is also undefined if the channel object can't be resolved, as described in Handle loading and errors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { useObject } from '@ably/pubsub-device/liveobjects/react';
const Scoreboard = () => {
const { value, object } = useObject<Game>();
if (!object) {
return <p>Loading...</p>;
}
return (
<>
<h1>{value?.title}</h1>
<p>Alice: {value?.scores?.alice ?? 0}</p>
<p>Bob: {value?.scores?.bob ?? 0}</p>
</>
);
};The component re-renders whenever the object, or any object nested within it, changes. The hook subscribes to a path rather than to a specific object instance, so it stays up to date when an object at that path is replaced.
Two properties of value are worth knowing:
- Its identity changes only when the subscribed data changes, so it is safe to use in the dependency arrays of hooks such as
useEffectanduseMemo. - It is a copy. The same data read by two different
useObjectcalls produces two snapshots that are not reference-equal. Compare fields rather than snapshots.
Subscribe to a nested object
Pass a selector function to subscribe to an object nested within the channel object. The selector receives the channel object as a PathObject and navigates to a descendant using get() or at(). The hook subscribes to the path the selector returns, and value and object refer to that path:
1
2
3
4
5
6
7
8
import type { LiveMap, PathObject } from '@ably/pubsub-device/liveobjects';
import { useObject } from '@ably/pubsub-device/liveobjects/react';
const BobScore = () => {
const { value } = useObject((obj: PathObject<LiveMap<Game>>) => obj.get('scores').get('bob'));
return <p>Bob: {value ?? 0}</p>;
};The component re-renders only when the data at that path changes. Select the narrowest path that a component renders to avoid unnecessary re-renders.
The selector must only navigate. Don't read values or update objects in it. The hook calls the selector on every render, and keeps its subscription for as long as the selector returns the same path.
Update objects
Use the object returned by the hook to update objects. It is a PathObject, so it has the same methods for updating data, such as set() and remove() on a LiveMap, increment() and decrement() on a LiveCounter, and batch() to apply several updates together.
object is undefined until the channel object has synchronized, or if it can't be resolved, so check it before you call a method on it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { LiveCounter, LiveMap } from '@ably/pubsub-device/liveobjects';
import { useObject } from '@ably/pubsub-device/liveobjects/react';
const NewGame = () => {
const { object } = useObject<Game>();
const startGame = () =>
object?.batch((ctx) => {
ctx.set('title', 'New game');
ctx.set('scores', LiveMap.create({ alice: LiveCounter.create(0), bob: LiveCounter.create(0) }));
});
return (
<button disabled={!object} onClick={startGame}>
Start a new game
</button>
);
};You don't need to update component state after an update. Every component that reads the changed path re-renders when the update is applied.
An update method throws an ErrorInfo straight away, before anything is sent, if the channel doesn't have the OBJECT_PUBLISH mode or the path doesn't hold an object of the right type, for example when you call increment() on a path with no LiveCounter. Otherwise it returns a promise, which rejects if the update fails. Call it from an async function to handle both cases in one place:
1
2
3
4
5
6
7
8
9
const { object } = useObject((obj: PathObject<LiveMap<Game>>) => obj.get('scores').get('alice'));
const incrementScore = async () => {
try {
await object?.increment(1);
} catch (error) {
console.error('Failed to update the score', error);
}
};Handle loading and errors
The channel object resolves asynchronously, after the channel attaches and the initial synchronization completes. The hook doesn't return a status field. Instead, derive the state from object and error:
| State | Condition |
|---|---|
| Loading | object is undefined and error is null |
| Failed | error is not null |
| Ready | object is defined |
When the hook is ready, value holds the data at the subscribed path. It is undefined if nothing exists at that path yet.
error is an ErrorInfo that describes why the channel object could not be resolved. For example, the client was created without the LiveObjects plugin, the channel doesn't have the OBJECT_SUBSCRIBE mode, or the initial synchronization failed:
1
2
3
4
5
6
7
8
9
10
11
12
13
const Scoreboard = () => {
const { value, object, error } = useObject<Game>();
if (error) {
return <p>Failed to load the game: {error.message}</p>;
}
if (!object) {
return <p>Loading...</p>;
}
return <p>Alice: {value?.scores?.alice ?? 0}</p>;
};Like the other channel hooks, useObject also returns connectionError and channelError, which hold the reason for the most recent connection or channel failure. connectionError is reset to null when the connection becomes connected or closed, and channelError when the channel becomes attached:
1
const { connectionError, channelError } = useObject<Game>();Type the channel object
If you use TypeScript, provide the shape of the channel object to get type-safe access to it. This is the same type you pass to channel.object.get<T>().
When you call useObject without a selector, pass the shape as a type parameter:
1
const { value, object } = useObject<Game>();When you pass a selector, annotate the selector's parameter instead. TypeScript checks the whole navigation chain, including the keys you pass to get(), and infers the types of value and object from the path the selector returns:
1
2
3
// value: number | undefined
// object: PathObject<LiveCounter> | undefined
const { value, object } = useObject((obj: PathObject<LiveMap<Game>>) => obj.get('scores').get('alice'));To avoid repeating the annotation, define a type alias for the channel object's PathObject:
1
2
3
type GameObject = PathObject<LiveMap<Game>>;
const { value, object } = useObject((obj: GameObject) => obj.get('scores').get('bob'));Without a type, the hook treats the channel object as a LiveMap whose entries can hold any value, so TypeScript can't check the keys you navigate to or the methods you call.
Options
Pass an options object as the only argument, or as the second argument after a selector:
1
2
3
4
5
const { value } = useObject((obj: GameObject) => obj.get('scores'), {
channelName: 'cup-tea-pot',
skip: !isSignedIn,
onChannelError: (error) => console.error(error.message),
});| Option | Description | Type |
|---|---|---|
| channelName | The name of the channel to use. A ChannelProvider for this channel must exist higher in the component tree. Defaults to the channel of the nearest ChannelProvider. | string |
| contextId | The ID of the PubSubClientProvider whose client to use, when you use multiple clients. Defaults to the provider without an ID. | string |
| skip | When true, the hook doesn't attach to the channel or resolve the channel object, and value and object are undefined. Defaults to false. | boolean |
| onConnectionError | Called with the reason when the connection becomes disconnected, suspended or failed. | (error: ErrorInfo) => unknown |
| onChannelError | Called with the reason when the channel becomes detached, suspended or failed. | (error: ErrorInfo) => unknown |
Return value
| Property | Description | Type |
|---|---|---|
| value | A plain-data snapshot of the subscribed path, as returned by compact(). undefined while loading, or if nothing exists at the path. | The compact type of the subscribed path, or undefined |
| object | The PathObject for the subscribed path, used to navigate and to update objects. undefined until the channel object has synchronized, or if it can't be resolved. | PathObject or undefined |
| error | The reason the channel object could not be resolved, or null. | ErrorInfo or null |
| connectionError | The reason for the most recent connection failure, or null. | ErrorInfo or null |
| channelError | The reason for the most recent channel failure, or null. | ErrorInfo or null |
Edge cases
- If the connection is
suspended,closing,closedorfailedwhen the component mounts, the hook waits, and resolves the channel object once the connection is usable again. Until then,objectisundefined. - Once resolved,
objectstays the same across a detach and reattach of the channel, so your component doesn't need to handle reattachment. - If
channelNamechanges,objectandvalueareundefineduntil the new channel's object resolves. The hook never returns data from the previous channel. - If the selector returns a different path, the hook unsubscribes from the old path and subscribes to the new one.
- If nothing exists at the subscribed path,
objectis still defined butvalueisundefined. Create the object, for example withset()on its parentLiveMap, before you call update methods on it. - With server-side rendering,
valueandobjectare alwaysundefinedon the server, because the hook resolves the channel object in an effect after the component mounts. The component renders its loading state on the server and in the first client render.
FAQ
Do I need to attach to the channel myself?
No. The hook attaches to the channel and waits for the initial synchronization before it returns object.
Can I use useObject without a ChannelProvider?
No. The channel must have a ChannelProvider higher in the component tree, which is where its channel modes are set. Use the channelName option to pick a channel other than the nearest ChannelProvider's, provided that channel also has a ChannelProvider above the component.
How do I avoid re-rendering on every change to the channel object?
Pass a selector that navigates to the narrowest path the component renders. The component then re-renders only when data at or below that path changes.
Why isn't value equal to a snapshot from another component?
Each useObject call produces its own snapshot, so two components that read the same data get two copies. Compare the fields you need, or use object when you need a stable reference to a path.
Related
- PathObject: navigate, read and update objects through paths.
- Typing: describe the shape of the channel object in TypeScript.
- Pub/Sub React Hooks: the providers and hooks for messages and presence.