Command Palette

Search for a command to run...

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

getServerSnapshot: rendering where there is no browser

renderToString runs here in the browser, but it follows the server rules: React uses getServerSnapshot and throws without it. In a real app the server HTML says Light, and a dark-mode user sees it switch right after hydration (Topic 24.10 shows how to avoid that flash). The <!-- --> comment is how React's server HTML separates two pieces of text.

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?

getServerSnapshot: rendering where there is no browser

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Without getServerSnapshot: Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.
With getServerSnapshot: <p>Light<!-- --> theme</p>