Full answer
Real-time data comes from outside React. A common beginner approach is useEffect that opens a socket and stores messages with setState. It works for one component, but each component opens its own connection, and with concurrent rendering a value read during render may differ from what another component saw (tearing).
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) is designed for external stores. subscribe(callback) registers a listener and returns an unsubscribe function. getSnapshot() returns the current value, and it must return the same reference when nothing changed, or React will loop. React calls getSnapshot during render and after changes, and it forces updates from the store to be synchronous, which keeps the UI consistent. The optional getServerSnapshot supports server rendering and hydration.
Store design:
- A module or class holds the connection, the list of listeners and an immutable snapshot (
{ status, messages }). - On each incoming message, create a new snapshot object (do not mutate the old one) and notify listeners.
- Connect lazily when the first listener subscribes and disconnect when the last one unsubscribes, so unused pages cost nothing.
- Reconnect with exponential backoff and jitter after a drop, and expose
status(connecting, open, closed) so the UI can show it. Resend the subscription and request missed messages after reconnecting, using a sequence number or last event id. - Parse and validate messages at the boundary. Cap the buffer size.
- For high frequency updates, batch (for example at animation frame) and use selectors so components read only what they need.
Alternatives: Server-Sent Events for one-way streams, polling for simple needs, and data libraries that integrate sockets with the cache (for example calling queryClient.setQueryData when a message arrives). Libraries such as Zustand and Redux are built on the same hook.
The example uses a fake socket made of timers, so no network is needed.
import { useSyncExternalStore } from 'react';
function createMessageStore(openSocket) {
let snapshot = { status: 'closed', messages: [] };
let socket = null;
const listeners = new Set();
function update(next) {
snapshot = { ...snapshot, ...next };
listeners.forEach((listener) => listener());
}
return {
subscribe(listener) {
listeners.add(listener);
if (listeners.size === 1) {
console.log('first subscriber: connecting');
update({ status: 'connecting' });
socket = openSocket({
onOpen: () => update({ status: 'open' }),
onMessage: (text) => update({ messages: [...snapshot.messages, text] }),
});
}
return () => {
listeners.delete(listener);
if (listeners.size === 0) {
console.log('last subscriber left: disconnecting');
socket.close();
update({ status: 'closed' });
}
};
},
getSnapshot: () => snapshot,
};
}
// A fake socket: opens after 10 ms and sends three messages.
function openFakeSocket({ onOpen, onMessage }) {
const timers = [setTimeout(onOpen, 10)];
['Lesson 1 published', 'Lesson 2 published', 'Quiz opened'].forEach((text, i) => {
timers.push(setTimeout(() => onMessage(text), 20 + i * 10));
});
return { close: () => timers.forEach(clearTimeout) };
}
const store = createMessageStore(openFakeSocket);
export default function Updates() {
const { status, messages } = useSyncExternalStore(store.subscribe, store.getSnapshot);
return (
<div>
<p>Status: {status}</p>
<ul>
{messages.map((message) => (
<li key={message}>{message}</li>
))}
</ul>
</div>
);
}The store connects when the component subscribes and disconnects when it unmounts. The check waited for the fake socket to finish. A real store would add reconnect with backoff. Output of the run: first subscriber: connecting after the connection delivered messages: Status: openLesson 1 publishedLesson 2 publishedQuiz opened last subscriber left: disconnecting
Key points
- Put the connection in a store outside React and read it with useSyncExternalStore.
- getSnapshot must return a cached, immutable value that changes only when data changes.
- Connect on the first subscriber and disconnect on the last one.
- Handle reconnect with backoff, missed messages, validation and bounded buffers.
- For high-frequency data, batch updates and select only what a component needs.
Common mistakes
- Returning a new object from getSnapshot on every call, which causes an infinite loop.
- Mutating the snapshot instead of creating a new one.
- Opening one connection per component.
- Not cleaning up the socket on unmount.
- Reconnecting immediately in a tight loop with no backoff.
Follow-ups
- What is tearing and how does useSyncExternalStore prevent it?
- How would you implement reconnect with exponential backoff and jitter?
- How would you feed socket messages into a TanStack Query cache?
Tips
- Mention tearing. It is the reason the hook exists.
- State the getSnapshot caching rule. It is the most common bug.
- Describe lazy connect and disconnect.