Command Palette

Search for a command to run...

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

Your own store, changed from outside React

Each component re-renders only when its selected value changes: adding an item doesn't re-render CouponLine. This is the core of how Zustand and react-redux work (Phase 15).

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?

Your own store, changed from outside React

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

CartBadge rendered: 0
CouponLine rendered: (none)
CartBadge rendered: 1
CouponLine rendered: HECTAL10