On the previous page we learned to update presence with our cursor location—let’s use it to render live cursors.
Switch to Room.tsx
and add the imported useOthers
hook to your
component.
/Room.tsx
// Get list of other usersconst others = useOthers();
useOthers
returns a list of information about the other users currently
online, such as presence. For example, you can find the first other user’s
cursor position here:
// { cursor: null }others[0].presence;
To render the cursors, we first need a cursor component. If you look inside
Cursor.tsx
you’ll find a simple component that does this using x
and y
coordinates.
<Cursor x={141} y={252} />
To draw them, we can map through others
, filtering for any cursors that are
equal to null
(therefore off-screen), and render each on-screen cursor. Switch
back to Room.tsx
and return the following code.
/Room.tsx
return ( <div style={{ width: "100vw", height: "100vh" }} onPointerMove={handlePointerMove} onPointerLeave={handlePointerLeave} > Cursor: {JSON.stringify(myPresence.cursor)} {others .filter((other) => other.presence.cursor !== null) .map(({ connectionId, presence }) => ( <Cursor key={connectionId} x={presence.cursor.x} y={presence.cursor.y} /> ))} </div>);
connectionId
is a unique number for each online user that can be used as a
key.
After adding this, hover over the preview windows to see functioning live cursors!
We can actually make these cursors even smoother, by requesting Liveblocks send
more frequent updates. We can do this in App.tsx
by adding the throttle
prop LiveblocksProvider
.
/App.tsx
<LiveblocksProvider publicApiKey={publicApiKey} throttle={16}>
Press the refresh button in the preview window to reload the client, and you should now be seeing smoother cursors!
The default throttle rate is 100ms, and above we’re decreasing it to 16ms. This is equivalent to a 60fps animation.
Presence isn’t only used for cursors, there are also a number of other different applications such as:
We use cookies to collect data to improve your experience on our site. Read our Privacy Policy to learn more.