Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.3 — useSyncExternalStore: Subscribing to Outside Stores
React · Example 1 of 4

useOnlineStatus with useSyncExternalStore

Firing a fake offline event doesn't change the real navigator.onLine, so the demo replaces the getter. That shows the point: React re-reads getSnapshot on each event, and both components update together.

useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?) reads a value that lives outside React (a browser API or a store library) and re-renders when it changes, without the tearing bugs that a hand-made effect-and-state subscription can have.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write useWindowWidth() with useSyncExternalStore, subscribing to resize, with a server snapshot of 1024.

02

Write usePageVisible() that returns true while the tab is visible, using document.visibilityState and the visibilitychange event.

03

Add a useCounterStore() hook to a createStore({ count: 0 }) store and render two <Count /> components plus a button that increments from outside React.

Explain it without notes

01

What do subscribe and getSnapshot each do, and when does React call them?

02

What is tearing, why could it happen in React 18, and how does useSyncExternalStore prevent it?

03

Why must the snapshot be cached, and what happens if it isn't?

04

When do you need getServerSnapshot, and what should it return?

useOnlineStatus with useSyncExternalStore

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Online / Save
Offline / Reconnecting...
Online / Save