Getting startedReact tutorial

//Live cursors using presence

Live cursors using presence

On the previous page we learned to update presence with our cursor location—let’s use it to render live cursors.

Getting others’ presence

Switch to Room.tsx and add the imported useOthers hook to your component.

Modify the code in /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;

Rendering the cursors

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.

Modify the code in /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>);

After adding this, hover over the preview windows to see functioning live cursors!

Throttle rate

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.

Modify the code in /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!

Other uses

Presence isn’t only used for cursors, there are also a number of other different applications such as: