SharedState Introduction
SharedState is a primitive that allows you to make clients that all see the same state of the data in real-time.
Introduction
The SharedState primitive can be used in React via the useSharedState
hook.
It works almost identically to React's useState
but it syncs the state across all the
clients subscribed to the same "channel"
Hello World
import { useSharedState } from '@airstate/react';
export function App() {
const [message, setMessage] = useSharedState('Hello World');
const changeMessage = () => {
setMessage('Hello Realtime');
}
return (
<>
<pre>
{message}
</pre>
<button onClick={changeMessage}>
Change Message
</button>
</>
);
}
By default, the unique identifier for this piece of state (known as a channel
) is set to be the
pathname
derived from window.location.href
An important limitation of this is that you can only have at most one SharedState without
an explicitly defined channel
on a page.
Concepts
We want people to move away from the concept of messages as a mental model for real-time collaborative state; the first thing we introduce is SharedState. You can think of SharedState as our version of Firebase Realtime DB. You can have "channels", and each channels can have a JSON object associated with it.
- SharedState automatically handle conflicts at the key level for this shared JSON object.
- SharedState currently uses yjs under the hood to store and sync JSON objects over AirState's YJS integration (currently undocumented).
Use Cases
With SharedState you are welcome to build anything you want where you need every client to be able to see the exact same state of the data.
It is typically using to build things like (not an exhaustive list):
- Shared ToDo Lists (like Google Keep)
- Whiteboards (like Miro)
- Real-time Settings & Configuration Preview
- Media Remote (like Spotify)
- Real-time Vector Graphics Editors (like Figma)
- Real-time Collaborative Node Editors (like ManyChat)
- Collaborative Mind Mapping Tools (like Mural)
- Interactive Presentation Builders (like Google Slides)
- Collaborative Database Schema Design Tools ()
- Watch Party Synchronization (like shared YouTube players)
- Collaborative Playlist Creation (like Spotify)
- Image Annotation Tools
- Document Feedback / Review Tools