Add multiplayer presence (live cursors/avatars) to your react application using yjs and hooks

Overview

y-presence

Easy way to add presence (live cursors/avatars) to any react application using react hooks.

Installation

yarn add y-presence
# or
npm i y-presence

Usage

Codesandbox demo/examples

For all the demos, you can open a new tab on your browser to observe how the presence updates in each example.

Using PresenceProvider

Wrap the components you'd like to provide access to y-presence hooks inside PresenceProvider in your React application.

// src/app.js

import * as Y from 'yjs'
import { PresenceProvider } from 'y-presence'

// Create the shared doc (from Yjs)
const doc = new Y.Doc()

// Create a provider
const provider = ...

// Get the provider's awareness API
const awareness = provider.awareness

export default function App() {
  return (
    <PresenceProvider awareness={awareness}>
      <SimpleRoom />
    </PresenceProvider>
  )
}

Using y-presence react hooks

y-presence comes with two hooks: useSelf() and useOthers() that are used to get information about self and other users connected in the room.

// src/app.js

import { useOthers, PresenceProvider } from 'y-presence'

...

export default function App() {
  return (
    <PresenceProvider awareness={awareness}>
      <SimpleRoom />
    </PresenceProvider>
  )
}

function SimpleRoom() {
  const others = useOthers()

  return <>There are currently {others.length} other people in the room.</>
}

y-presence react hooks

  • useSelf(): The useSelf hook accepts an initial presence object and returns an object containing information about the current user (represented as self) and a function to update the user's presence. The update function doesn't require the full presence object to update it. You may only send the presence properties that you'd like changed in the presence.

    The self object contains the user client/connection id and a field to store a presence object. It looks like the following:

    User<T> = {
      id: number, // The client id associated to the user
      presence?: T // The user presence
    }

    Example:

    import { useSelf } from 'y-presence'
    
    // Define the presence object (ignore if not typescript)
    type CursorPresence = {
      x: number
      y: number
    }
    
    export default function Room() {
      const { self, updatePresence } = useSelf<CursorPresence>({
        x: 0,
        y: 0,
      })
    
      // updatePresence doesn't require the full presence object
      updatePresence({ x: 1 })
    
      updatePresence({ y: 2 })
    
      return (
        <>
          <p>Client id: {self.id}</p>
          <p>Presence: {self.presence}</p>
        </>
      )
    }
  • useOthers(): The useOthers hook returns an array of users that are currently connected in the room (excluding yourself). Each user object in the array contains the client/connection id and the presence information associated to the user. The user object looks like the following:

    User<T> = {
      id: number, // The client id associated to the user
      presence?: T // The user presence
    }

    Example

    import { useOthers } from 'y-presence'
    
    // Define the presence object (ignore if not typescript)
    type CursorPresence = {
      x: number
      y: number
    }
    
    export default function Room() {
      const others = useOthers<CursorPresence>()
    
      return (
        <>
          <p>Number of other users: {others.length}</p>
    
          {others.map(({ id, presence }) => {
            if (!presence) return null
    
            return <Cursor key={id} x={presence.x} y={presence.y} />
          })}
        </>
      )
    }

Credits

Huge thanks to @steveruizok's perfect-cursor's demo that inspired me to write this library. The two react hooks and their structure are also very much inspired by Liveblocks’s react implementation of their multiplayer API.

You might also like...

A web application to search all the different countries in the world and get details about them which can include languages, currencies, population, domain e.t.c This application is built with CSS, React, Redux-Toolkit and React-Router.

A web application to search all the different countries in the world and get details about them which can include languages, currencies, population, domain e.t.c This application is built with CSS, React, Redux-Toolkit and React-Router.

A web application to search all the different countries in the world and get details about them which can include languages, currencies, population, domain e.t.c This application is built with CSS, React, Redux-Toolkit and React-Router. It also includes a theme switcher from light to dark mode.

Jun 5, 2022

This is the Full Stack Application that we're building as a part of Praveen's Live Stream.

Community Class Room Intro Motivation Tech Stack Used PreRequisites Installation Instructions Features Marketing Public Pages Basic Design from the Th

Apr 24, 2022

Space Traveller hub is a web application that works with the real live data from the SpaceX API

Space Traveller hub is a web application that works with the real live data from the SpaceX API

Space Traveller hub is a web application that works with the real live data from the SpaceX API. It's a web application for a company that provides commercial and scientific space travel services.

Feb 8, 2022

🎉 toastify-react-native allows you to add notifications to your react-native app (ios, android) with ease. No more nonsense!

🎉 toastify-react-native allows you to add notifications to your react-native app (ios, android) with ease. No more nonsense!

toastify-react-native 🎉 toastify-react-native allows you to add notifications to your react-native app (ios, android) with ease. No more nonsense! De

Oct 11, 2022

Drop-in replacements for @apollo/client's useQuery, useMutation and useSubscription hooks with reduced overhead and additional functionality.

apollo-augmented-hooks Drop-in replacements for @apollo/client's useQuery, useMutation and useSubscription hooks with reduced overhead and additional

Nov 18, 2022

Fast, tiny and solid hooks system for Javascript and Node.js

Fast, tiny and solid hooks system for Javascript and Node.js

Uncino 🪝 Fast, tiny and solid hooks system for Javascript and NodeJS Uncino is italian word for hook Do you know Wordpress hooks system? Uncino is a

Dec 7, 2022

preact.js with hooks and ES2021, without compilers

naked preact preact.js with hooks, without compilers Web development should be simple. No compilers, just ES2021 and preact+hooks. See comments in the

Jun 16, 2022

A npm package to increase the developer experience and consistency by providing a set of hooks that can be opted-in the development lifecycle.

@jeliasson/husky-hooks This npm package aims to increase the developer experience and consistency by providing a set of hooks that can be opted-in the

Dec 6, 2022

A library of RxJS-related hooks

rxooks GADZOOKS! RXOOKS! (Basically every other iteration of "rxjs", "rx", "react", and "hooks" was taken) This is a library of hooks that are useful

Nov 28, 2022
Owner
Nimesh Nayaju
Nimesh Nayaju
React components and hooks for creating VR/AR applications with @react-three/fiber

@react-three/xr React components and hooks for creating VR/AR applications with @react-three/fiber npm install @react-three/xr These demos are real,

Poimandres 1.4k Jan 4, 2023
📋 React Hooks for forms validation (Web + React Native)

English | 繁中 | 简中 | 日本語 | 한국어 | Français | Italiano | Português | Español | Русский | Deutsch | Türkçe Features Built with performance and DX in mind

React Hook Form 32.4k Dec 29, 2022
Built a covid-19 trcaker app using React.js implementing hooks and materail UI

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Aditya Dond 1 Dec 21, 2021
⚛️ Hooks for building fast and extendable tables and datagrids for React

Hooks for building lightweight, fast and extendable datagrids for React Enjoy this library? Try them all! React Query, React Form, React Charts Visit

Tanner Linsley 20.3k Jan 3, 2023
⚛️ Hooks for fetching, caching and updating asynchronous data in React

Hooks for fetching, caching and updating asynchronous data in React Enjoy this library? Try the entire TanStack! React Table, React Form, React Charts

Tanner Linsley 32.1k Jan 9, 2023
Fully typed hooks and utility functions for the React Native StyleSheet API

react-native-style-utilities Fully typed hooks and utility functions for the React Native StyleSheet API npm i react-native-style-utilities ESLint Set

Marc Rousavy 73 Dec 17, 2022
React Hooks — 👍

Collaborative editing for your app. Support on Kickstarter! ?? react-use Collection of essential React Hooks. Port of libreact. Translations: ???? 汉语

Vadim Dalecky 34.9k Jan 3, 2023
React Hooks library for remote data fetching

Introduction swr.vercel.app SWR is a React Hooks library for remote data fetching. The name “SWR” is derived from stale-while-revalidate, a cache inva

Vercel 25.2k Jan 4, 2023
React Hooks tutorial for beginners.

React Hooks for Beginners git clone <url> Clone into the repo code react-hooks Open the folder in VS Code npm install Install the dependencies npm sta

Mohammad Muazam 2 Oct 10, 2022
A custom ESLint rule to allow static deps in React Hooks ⚛️

eslint-plugin-react-hooks-static-deps A custom ESLint rule to allow static deps in React Hooks ⚛️ Motivation react-hooks/exhaustive-deps is a really n

Stoïk 3 Apr 5, 2022