Course outline

React / Performance and trustworthy boundaries / Lesson 21

External store snapshots and subscription contracts

Connect an external store through stable snapshots, cleanup, and an explicit server hydration contract.

About 23 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Describe the external snapshot and subscription contracts.
  • Avoid unstable snapshots and leaking listeners.
  • Explain server snapshot consistency and request isolation.
  • Implement stable immutable snapshots and symmetric subscriptions for an external store.
  • Match server and hydration snapshots while isolating private request state.

Identify the external owner

An external store owns data outside React and notifies consumers when that data changes. useSyncExternalStore integrates its subscription and snapshot with React rendering. Prefer ordinary React state when React already owns the value; an extra store introduces an independent lifecycle and a consistency contract. First identify who writes the value, who subscribes, and what a consumer should observe after a change.

Implement a bounded store

This educational store uses a primitive snapshot and a set of listeners. Each subscription returns cleanup for the same listener, and the update changes the value before notifying subscribers. Repeated snapshot reads return the same primitive while the store has not changed. The module is illustrative for a browser-only shared counter, not a per-user server data store.

javascript Illustrative external store module
const listeners = new Set();
let count = 0;
export function subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }
export function getSnapshot() { return count; }
export function increment() { count += 1; listeners.forEach(listener => listener()); }
Expected output
Each increment increases the snapshot by one.

Listeners are registered and removed symmetrically; increment publishes the changed value before notifications.

Read the store in a component

The component passes stable module-level functions to useSyncExternalStore and renders the returned value. The server snapshot is zero for this controlled example; server HTML and the initial hydration snapshot must agree. If a real server renders preloaded data, transfer the same initial snapshot safely to the client. Do not expose private data in serialized HTML unless the recipient is authorized.

jsx Component module for a React host
import { useSyncExternalStore } from "react";
import { subscribe, getSnapshot, increment } from "./store";
const getServerSnapshot = () => 0;
export default function Counter() {
  const count = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
  return <button onClick={increment}>Count: {count}</button>;
}
Expected output
Initially Count: 0; clicking increments the displayed count.

The Hook subscribes to the store and reads its snapshot; the button changes it through the store API.

Preserve snapshot identity

React compares snapshot values to determine whether the observable data changed. Returning a fresh object on every read even when the store has not changed can cause repeated rendering and a cached-snapshot diagnostic. For mutable backing data, cache an immutable snapshot and replace it only when relevant data changes. Keep subscribe stable to avoid unnecessary resubscriptions and ensure its cleanup removes the original listener.

Verify hydration and isolation

Test subscription, update, unmount and remount with controlled data; confirm that removed consumers no longer receive notifications. During server rendering compare the server snapshot with the first hydration snapshot, then allow the client to observe later changes. A process-wide mutable module can leak one request’s data into another: create request-scoped stores for private server data and make ownership explicit. The example does not establish a production storage or authorization design.

Identify the store and its observable contract

An external store owns data outside React and offers a way to read its current snapshot and subscribe to changes. useSyncExternalStore connects that contract to React rendering: subscribe registers a callback and returns an unsubscribe function, while getSnapshot returns the value the consumer observes. When the store changes, it updates its data before notifying listeners so a subsequent snapshot read sees the new value. If React already owns the value and no external subscriber needs it, ordinary state is often simpler than creating another store and consistency contract.

Name the owner, writers, subscribers, and lifetime. A browser-only shared counter can be a small module-level example, but that does not make a process-wide mutable singleton safe for per-user server data. A store API should say which changes trigger notification, what a snapshot contains, and how a subscriber leaves. Do not mutate a snapshot after returning it. Test two consumers and verify that unsubscribing one does not remove the other. An external store does not automatically authorize a write, persist data, or synchronize a remote service.

Return a stable immutable snapshot

While the store has not changed, repeated getSnapshot calls must return the same value under Object.is. A primitive number naturally satisfies that requirement when unchanged. If getSnapshot creates a new object or array on every call, React sees a different reference even when the backing data is identical; this can cause repeated updates and a cached-snapshot diagnostic. For mutable backing data, build an immutable snapshot when relevant data changes and return that cached object until the next relevant change. An old snapshot should remain unchanged after a later update.

Notify subscribers after replacing the snapshot, not before, so their reads observe the new data. If an update is a documented no-op, avoid inventing a new snapshot or notification merely to simulate change. For nested data, copy the changed path or otherwise maintain immutability throughout the returned snapshot. Equality of references is evidence of identity, not proof that the domain value is correct: also test the fields and business rule. A store that returns a stable object but mutates its contents in place violates the snapshot contract even if Object.is reports equality.

Make subscription and cleanup symmetric

subscribe receives a callback, registers it, and returns cleanup that removes that same callback. Keep subscribe’s function identity stable when possible; passing a different function on every render can cause unnecessary unsubscribe and resubscribe cycles. A module-level function or a stable store method can be appropriate for a browser-scoped store. If the store instance itself changes, define and test the intended replacement lifecycle rather than hiding that change behind an empty dependency list.

A listener may be removed while another remains subscribed, and cleanup should not delete unrelated listeners. On unmount, React invokes the returned unsubscribe; test mount, update, unmount, and remount with a controlled store. Avoid making getSnapshot perform a write or trigger notification because React may read it repeatedly. If notification callbacks can themselves cause updates, define ordering and error handling in the store’s actual contract. A count of listener calls is useful evidence for cleanup but does not replace checking the committed interface.

Match hydration and isolate requests

For server rendering, getServerSnapshot supplies the initial snapshot used on the server and during client hydration. The corresponding initial data must agree across those two stages; if real preloaded data is used, transfer the authorized snapshot safely to the appropriate client. After hydration the client store can publish later changes through getSnapshot. Omitting getServerSnapshot means the component cannot render on the server through this Hook’s contract. A fixed zero is suitable only for a fixture whose server and hydration initial value is truly zero.

Do not keep private request data in a mutable process-wide module singleton that can be reused by another server request. Create request-scoped store instances, authorize each request, and serialize only data intended for that recipient. Snapshot consistency is not an authorization policy or a cache freshness guarantee. Coordinate identifier and data serialization with the chosen framework and test a direct server-rendered load. Never put credentials in the serialized initial snapshot merely because it originated on the server.

Test the complete snapshot lifecycle

Start with a controlled store and call getSnapshot twice without an update; assert the same primitive or object identity and correct fields. Subscribe two listeners, change the store, and verify that the new snapshot is published before both are notified. Unsubscribe one, update again, and verify only the remaining listener receives the notification. Check no-op behavior, old-snapshot immutability, and a component’s committed display after an update. A fake store should model the real contract rather than claiming a production data service was exercised.

For SSR, render and hydrate with the same authorized initial snapshot, observe diagnostics, and then publish a client update. Test two synthetic server requests with isolated stores to detect cross-request leakage. React may recheck external snapshots around concurrent work; do not infer that external mutations have transition priority or use this Hook as a substitute for a documented data layer. The examples below target React 18.3.1 or synthetic store fixtures and are non-runnable here; no server, browser, or live service execution is claimed.

20 worked examples

1. Primitive snapshot

Problem: Read the same primitive snapshot twice without changing the store.

  1. The backing count does not change between reads.
  2. Both calls return the same primitive value under Object.is.
javascript Synthetic React 18.3.1 external-store fixture.
let count = 0;
function getSnapshot() { return count; }
const first = getSnapshot();
const second = getSnapshot();
const same = Object.is(first, second);

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: first and second are 0 and same is true.

Why this result follows: The backing count does not change between reads. Both calls return the same primitive value under Object.is.

2. Cached object snapshot

Problem: Reuse an immutable snapshot object until relevant data changes.

  1. getSnapshot returns the stored object instead of allocating a new one.
  2. No update replaces that object between the two reads.
javascript Synthetic React 18.3.1 external-store fixture.
let snapshot = { count: 0 };
function getSnapshot() { return snapshot; }
const first = getSnapshot();
const second = getSnapshot();
const same = Object.is(first, second);

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: same is true and both reads contain count 0.

Why this result follows: getSnapshot returns the stored object instead of allocating a new one. No update replaces that object between the two reads.

3. Fresh object bug

Problem: Identify unstable identity when an unchanged store allocates on every read.

  1. Each call creates a new object reference.
  2. React can interpret the changing identity as a changed snapshot even without a store update.
javascript Synthetic React 18.3.1 external-store fixture.
const backing = { count: 0 };
function getSnapshot() { return { count: backing.count }; }
const first = getSnapshot();
const second = getSnapshot();
const same = Object.is(first, second);

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: same is false despite both counts being 0.

Why this result follows: Each call creates a new object reference. React can interpret the changing identity as a changed snapshot even without a store update.

4. Replace on update

Problem: Publish a new immutable snapshot while preserving the old one.

  1. increment creates a replacement object rather than mutating old.
  2. The stored snapshot reference changes only with the relevant value.
javascript Synthetic React 18.3.1 external-store fixture.
let snapshot = { count: 0 };
const old = snapshot;
function increment() { snapshot = { count: snapshot.count + 1 }; }
increment();
const next = snapshot;

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: old.count is 0, next.count is 1, and the objects differ.

Why this result follows: increment creates a replacement object rather than mutating old. The stored snapshot reference changes only with the relevant value.

5. No-op update

Problem: Keep snapshot identity when a requested value is already current.

  1. The requested value equals the current count.
  2. The documented no-op branch does not replace the snapshot.
javascript Synthetic React 18.3.1 external-store fixture.
let snapshot = { count: 2 };
function setCount(value) { if (value !== snapshot.count) snapshot = { count: value }; }
const old = snapshot;
setCount(2);
const same = Object.is(old, snapshot);

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: same is true and count remains 2.

Why this result follows: The requested value equals the current count. The documented no-op branch does not replace the snapshot.

6. Notify after update

Problem: Ensure a listener reads the new value when notified.

  1. The update changes count before invoking listeners.
  2. The listener therefore reads the published value rather than the old one.
javascript Synthetic React 18.3.1 external-store fixture.
let count = 0;
const seen = [];
const listeners = new Set([() => seen.push(count)]);
function increment() { count += 1; listeners.forEach(listener => listener()); }
increment();

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: count is 1 and seen is [1].

Why this result follows: The update changes count before invoking listeners. The listener therefore reads the published value rather than the old one.

7. Unsubscribe one listener

Problem: Remove the registered callback without removing a different subscriber.

  1. stopA closes over the callback registered for a.
  2. Deleting that callback does not remove the separate b listener.
javascript Synthetic React 18.3.1 external-store fixture.
const listeners = new Set();
const a = () => {}; const b = () => {};
function subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }
const stopA = subscribe(a); subscribe(b); stopA();

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: The set contains b and no longer contains a.

Why this result follows: stopA closes over the callback registered for a. Deleting that callback does not remove the separate b listener.

8. Unstable subscribe

Problem: Recognize an avoidable resubscription when a function is recreated each render.

  1. The arrow wrapper is allocated during every Viewer render.
  2. A stable store method or appropriately stable function avoids this unnecessary identity change.
jsx Synthetic React 18.3.1 external-store fixture.
function Viewer({ store }) {
  const value = React.useSyncExternalStore(callback => store.subscribe(callback), store.getSnapshot);
  return <p>{value}</p>;
}
// The inline subscribe wrapper is a new function on each render.

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: React may unsubscribe and resubscribe when the subscribe function identity changes.

Why this result follows: The arrow wrapper is allocated during every Viewer render. A stable store method or appropriately stable function avoids this unnecessary identity change.

9. Stable subscribe

Problem: Pass stable store functions to a browser-scoped consumer.

  1. The functions are declared outside the component.
  2. React can retain the subscription unless the store contract requires a change.
jsx Synthetic React 18.3.1 external-store fixture.
const listeners = new Set();
let count = 0;
function subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }
function getSnapshot() { return count; }
function Counter() { const value = React.useSyncExternalStore(subscribe, getSnapshot); return <p>{value}</p>; }

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: The consumer reads the current count and uses the same subscribe function across its renders.

Why this result follows: The functions are declared outside the component. React can retain the subscription unless the store contract requires a change.

10. React consumer update

Problem: Render an external primitive snapshot and update it through the store API.

  1. The Hook subscribes and reads the store snapshot.
  2. The click invokes the store API, which publishes the changed value.
jsx Synthetic React 18.3.1 external-store fixture.
function Counter({ store }) {
  const count = React.useSyncExternalStore(store.subscribe, store.getSnapshot);
  return <button type="button" onClick={store.increment}>Count: {count}</button>;
}
// A stable fake store starts at 0 and publishes 1 on increment.

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: Initially the button reads Count: 0; after the store update commits it reads Count: 1.

Why this result follows: The Hook subscribes and reads the store snapshot. The click invokes the store API, which publishes the changed value.

11. Mutated snapshot bug

Problem: Show why stable identity alone cannot make an object snapshot immutable.

  1. Both variables refer to the same object.
  2. Changing its field alters the value observed through the earlier reference.
javascript Synthetic React 18.3.1 external-store fixture.
const snapshot = { count: 0 };
const old = snapshot;
snapshot.count = 1;
const same = Object.is(old, snapshot);

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: same is true but old.count is now 1, so the prior snapshot was mutated.

Why this result follows: Both variables refer to the same object. Changing its field alters the value observed through the earlier reference.

12. Copy nested state

Problem: Replace the changed nested path in an immutable snapshot.

  1. The new root and changed user object are distinct.
  2. The old snapshot and its nested user are not modified.
javascript Synthetic React 18.3.1 external-store fixture.
const old = { user: { name: "Ada", active: false }, version: 1 };
const next = { ...old, user: { ...old.user, active: true }, version: 2 };

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: next.user.active is true while old.user.active remains false.

Why this result follows: The new root and changed user object are distinct. The old snapshot and its nested user are not modified.

13. Server snapshot match

Problem: Use the same initial primitive for server rendering and hydration.

  1. Both stages use the same initial primitive value.
  2. A later client store update can be observed separately after hydration.
javascript Synthetic React 18.3.1 external-store fixture.
const serverSnapshot = 0;
const hydrationSnapshot = 0;
const matches = Object.is(serverSnapshot, hydrationSnapshot);

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: matches is true.

Why this result follows: Both stages use the same initial primitive value. A later client store update can be observed separately after hydration.

14. Server snapshot mismatch

Problem: Detect inconsistent initial server and hydration data in a fixture.

  1. The server rendered count 3 while hydration starts from 0.
  2. The integration must transfer matching initial data before claiming a valid hydration contract.
javascript Synthetic React 18.3.1 external-store fixture.
const serverSnapshot = 3;
const hydrationSnapshot = 0;
const matches = Object.is(serverSnapshot, hydrationSnapshot);

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: matches is false.

Why this result follows: The server rendered count 3 while hydration starts from 0. The integration must transfer matching initial data before claiming a valid hydration contract.

15. Request-scoped stores

Problem: Keep private synthetic values separate for two server requests.

  1. Each factory call creates a separate closure for its value.
  2. Updating one request’s store does not mutate the other instance.
javascript Synthetic React 18.3.1 external-store fixture.
function createStore(initial) { let value = initial; return { getSnapshot: () => value, set: next => { value = next; } }; }
const first = createStore("user-a");
const second = createStore("user-b");
first.set("updated-a");

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: first reads updated-a while second still reads user-b.

Why this result follows: Each factory call creates a separate closure for its value. Updating one request’s store does not mutate the other instance.

16. Singleton leakage risk

Problem: Illustrate why one process-wide mutable value is unsuitable for private request state.

  1. Both calls write the same module-level variable.
  2. Concurrent or reused server requests need isolated state rather than this singleton.
javascript Synthetic React 18.3.1 external-store fixture.
let currentUser = null;
function setUser(value) { currentUser = value; }
setUser("user-a");
setUser("user-b");
const observed = currentUser;

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: observed is user-b, demonstrating that the second write replaced the shared value.

Why this result follows: Both calls write the same module-level variable. Concurrent or reused server requests need isolated state rather than this singleton.

17. Safe initial projection

Problem: Serialize only an authorized initial snapshot field for a client.

  1. The client snapshot is explicitly projected from the server record.
  2. Real access must be authorized before the selected data is delivered.
javascript Synthetic React 18.3.1 external-store fixture.
const serverRecord = { count: 3, token: "synthetic-secret" };
const clientInitial = { count: serverRecord.count };

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: clientInitial contains count 3 and no token field.

Why this result follows: The client snapshot is explicitly projected from the server record. Real access must be authorized before the selected data is delivered.

18. No server snapshot

Problem: Recognize the server-rendering requirement when using the external-store Hook.

  1. The Hook requires getServerSnapshot for server rendering.
  2. The integration must supply matching server and hydration data for SSR.
jsx Synthetic React 18.3.1 external-store fixture.
function Counter({ store }) {
  const count = React.useSyncExternalStore(store.subscribe, store.getSnapshot);
  return <p>{count}</p>;
}
// This browser-only fixture supplies no getServerSnapshot.

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: The fixture is suitable only for a client-only path unless a server snapshot is supplied.

Why this result follows: The Hook requires getServerSnapshot for server rendering. The integration must supply matching server and hydration data for SSR.

19. Two listener notifications

Problem: Publish a snapshot to two subscribers after a controlled update.

  1. The snapshot changes before the set is iterated.
  2. Both registered callbacks read the new value when notified.
javascript Synthetic React 18.3.1 external-store fixture.
let snapshot = 0;
const seen = [];
const listeners = new Set([() => seen.push(`a:${snapshot}`), () => seen.push(`b:${snapshot}`)]);
snapshot = 1;
listeners.forEach(listener => listener());

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: seen is ["a:1", "b:1"] in insertion order.

Why this result follows: The snapshot changes before the set is iterated. Both registered callbacks read the new value when notified.

20. Unmount test plan

Problem: Verify cleanup and remount behavior with a controlled external store.

  1. Unmount should invoke the subscription cleanup.
  2. The later update tests that the removed callback is no longer registered.
javascript Synthetic React 18.3.1 external-store fixture.
const test = { steps: ["mount", "update", "unmount", "update", "remount"], expected: "removed consumer receives no later notification", executed: false };

Trace the snapshot and subscription contract; no browser or server execution is claimed.

Expected result: The fixture specifies the lifecycle check and records that it was not executed.

Why this result follows: Unmount should invoke the subscription cleanup. The later update tests that the removed callback is no longer registered.

Common errors and fixes

Repeated renders report an uncached snapshot.

Why it happens
The snapshot function creates a fresh object on every read.
How to fix it
Cache an immutable snapshot until its data changes.
Prevent it next time
Test repeated reads without a store update.

Listeners accumulate after navigation.

Why it happens
The subscription does not remove the registered callback.
How to fix it
Return cleanup that removes the same callback.
Prevent it next time
Test unmount and remount with listener counts.

Initial client content differs from server content.

Why it happens
Server and hydration snapshots do not match.
How to fix it
Transfer the same initial snapshot safely to the client.
Prevent it next time
Test direct server-rendered loads with controlled data.

20 practice exercises

1. A snapshot returns a new array on every read although the store is unchanged. What should change?

Show hint

Compare the object identity returned by repeated reads with no store change.

Show worked solution

Cache an immutable array snapshot and reuse it until a relevant update replaces it. Verify repeated reads have stable identity and a real update produces a changed snapshot and notification.

Cache an immutable array snapshot and return that same array until relevant data changes. On a real update replace it with a new immutable array before notifying listeners. Test stable identity across unchanged reads, the new contents and identity after an update, and preservation of the old array.

Check your solution

  • Unchanged reads return the same array reference.
  • A real update publishes a new array and notification without mutating the old one.

2. Can the example module hold private data for every server request?

Show hint

Consider the lifetime of a mutable module in a server process.

Show worked solution

No. A long-lived server module can be shared by requests. Create request-scoped state, authorize access and transfer only the appropriate initial data to the corresponding client.

A long-lived server module may serve multiple requests, so a private user value in a process-wide singleton can be overwritten or exposed across requests. Create request-scoped stores, authorize access, and transfer only the appropriate initial snapshot to each client.

Check your solution

  • Private store instances are scoped to requests.
  • The client receives only authorized initial data.

3. A value is already owned only by one React component. Decide whether it needs an external store.

Show hint

An extra owner adds a subscription and consistency contract.

Show worked solution

Prefer ordinary React state when no external writer or subscriber requires a separate store. Identify the actual owner and consumers before introducing useSyncExternalStore. A new store can be justified for genuinely external data, but it is not needed merely to hold a local counter.

Check your solution

  • The value’s owner and consumers are identified.
  • A separate store has a concrete external responsibility.

4. Define subscribe and cleanup for a store with a Set of listeners.

Show hint

Remove the same callback that was registered.

Show worked solution

Add the supplied listener to the Set and return a function that deletes that listener. Subscribe two distinct listeners, invoke the first cleanup, and verify the second remains registered. On component unmount the Hook can call the returned cleanup for its own subscription.

Check your solution

  • The registered callback is removed by its cleanup.
  • Unrelated listeners remain registered.

5. A count store changes from zero to one. Specify update and notification order.

Show hint

Publish the new value before notifying subscribers.

Show worked solution

Set the current count to 1 first, then invoke the registered callbacks. Each listener that reads getSnapshot during notification sees 1 rather than 0. Test the resulting committed component display separately from the store’s callback sequence.

Check your solution

  • The snapshot is 1 before callbacks run.
  • The consumer eventually displays the new count.

6. getSnapshot returns a fresh {count:0} on every read without a store update. Explain and repair the contract.

Show hint

Object.is sees distinct object references.

Show worked solution

Cache an immutable snapshot object and return the same object while its relevant data is unchanged. Replace it with a new immutable object when count changes. Two reads without an update then compare equal by identity, while a real update produces the new count and reference.

Check your solution

  • Unchanged reads return the same object.
  • A real change replaces the snapshot.

7. A store mutates snapshot.count in place but returns the same object. Explain why stable identity is insufficient.

Show hint

Old readers still reference the object being changed.

Show worked solution

Create a new snapshot rather than mutating the object that was already returned. Otherwise an earlier reference unexpectedly sees the changed count and React may not detect a changed value through Object.is. Test the old field value as well as the new reference and domain result.

Check your solution

  • The old snapshot remains unchanged.
  • A relevant change yields a new snapshot identity.

8. A cached snapshot has nested user.active=false. Update it to true without changing the old snapshot.

Show hint

Copy the changed path, including the nested user object.

Show worked solution

Return a new root such as { ...old, user: { ...old.user, active: true } } and publish it as the next cached snapshot. Verify next.user.active is true and old.user.active remains false. Notify listeners only after the replacement is ready.

Check your solution

  • The new nested value is true.
  • The old nested value remains false.

9. A setCount operation receives the current value 2 again. Define a no-op policy for identity and notifications.

Show hint

Do not manufacture a change when the observable data is unchanged.

Show worked solution

Under the stated no-op policy, retain the existing snapshot object and skip notification when the requested count equals 2. Test that repeated reads have the same identity and that a later change to 3 replaces the snapshot and notifies. Document this policy for consumers.

Check your solution

  • Setting 2 retains the current snapshot.
  • Changing to 3 produces the documented notification.

10. A component creates callback => store.subscribe(callback) on every render. Explain the lifecycle cost.

Show hint

A new function identity can cause resubscription.

Show worked solution

Use a stable store method or a suitably stable subscribe function when the store instance is unchanged. React may unsubscribe and resubscribe if a different subscribe function is passed on rerender. Test cleanup and replacement when the actual store instance changes.

Check your solution

  • Unrelated renders do not need a fresh subscription function.
  • A changed store has an explicit replacement lifecycle.

11. Two components subscribe to the same store and one unmounts. Define the expected listener behavior.

Show hint

Each subscription owns its own cleanup.

Show worked solution

Unmounting the first component should remove its callback while leaving the second active. After the next update, verify the removed listener receives no notification and the remaining component observes the new snapshot. Finally unmount the second and confirm no listener remains.

Check your solution

  • The first listener is removed independently.
  • The second continues until its own cleanup.

12. A store’s getSnapshot increments a counter every time it is read. Explain why this is unsafe.

Show hint

Snapshot reads may happen repeatedly during rendering coordination.

Show worked solution

Make getSnapshot a pure read of the current cached snapshot. A read that mutates data or notifies listeners can change the store merely because React checks it, producing inconsistent results or repeated work. Put updates in an explicit store operation and notify after publication.

Check your solution

  • getSnapshot does not mutate the store.
  • An explicit update owns mutation and notification.

13. A browser-only counter store starts at zero. Connect a component using useSyncExternalStore.

Show hint

Pass stable subscribe and getSnapshot functions to the Hook.

Show worked solution

Call useSyncExternalStore(store.subscribe, store.getSnapshot) in the component and render its returned count. A button can call the store’s increment method. Starting at 0, one published increment should lead to Count: 1 after the update commits in a configured client host.

Check your solution

  • The component reads the external snapshot.
  • The store update is reflected after commit.

14. A server renders count 3 but hydration uses count 0. Identify the problem and repair.

Show hint

The server snapshot must agree with the hydration snapshot.

Show worked solution

Transfer the authorized initial count 3 to the corresponding client and have getServerSnapshot return matching data during hydration. Test the server HTML, parsed DOM, hydration diagnostics, and a later client update. Do not silently substitute zero for real preloaded data.

Check your solution

  • Server and hydration begin with count 3.
  • Later client updates use the store’s current snapshot.

15. A component uses useSyncExternalStore without getServerSnapshot and is rendered on the server. What is missing?

Show hint

Server rendering requires the initial server snapshot contract.

Show worked solution

Supply getServerSnapshot for an SSR path, returning data that matches the client’s hydration snapshot, or use a documented client-only boundary when appropriate. Do not assume the browser-only example proves SSR support. Verify the actual framework’s serialization and hydration behavior.

Check your solution

  • The SSR path has a server snapshot.
  • The server and hydration values agree.

16. A server module stores the current private user in a mutable global. Explain the cross-request risk.

Show hint

A long-lived module can serve more than one request.

Show worked solution

Create a store instance scoped to each request and authorize access to its data. A process-wide mutable variable can be overwritten by another request and leak or mix users’ state. Test two synthetic request stores with independent updates and controlled lifecycle.

Check your solution

  • Each request receives a separate store instance.
  • One request’s update does not change the other’s snapshot.

17. An initial store snapshot contains count and an access token. Decide what reaches the browser.

Show hint

Serialized client data is visible to the recipient.

Show worked solution

After authorizing the request, project only the count or other permitted public fields into the client’s initial snapshot. Keep the token on the server and inspect the actual serialized payload. Matching hydration data does not justify exposing credentials or private fields.

Check your solution

  • The client snapshot excludes the token.
  • The initial count remains consistent for hydration.

18. A store notifies before replacing its snapshot. Explain the observable failure and correction.

Show hint

Listeners may read immediately when called.

Show worked solution

Replace the cached snapshot first and then notify subscribers. If notification happens first, a listener can read the old value and miss or delay the intended update. Test the value observed inside a synthetic listener and the later committed component output.

Check your solution

  • Listeners read the new snapshot during notification.
  • The interface reflects the published value after commit.

19. A store uses an immutable snapshot but violates a nonnegative quantity rule. Explain what identity tests miss.

Show hint

Immutability and domain validity are separate.

Show worked solution

A new object containing quantity -1 can satisfy reference-change expectations while breaking the business invariant. Test the actual field and boundary rule as well as old-snapshot preservation and notification. Enforce any real server-side inventory constraints separately.

Check your solution

  • The quantity invariant is asserted.
  • The previous snapshot remains unchanged.

20. Design a test covering unchanged reads, two subscribers, cleanup, and a later update.

Show hint

Verify identity, values, and listener ownership together.

Show worked solution

Read the snapshot twice and assert stable identity and fields, subscribe A and B, publish a change, and verify both observe the new value. Unsubscribe A, publish again, and assert only B is notified; then clean up B. Use a controlled store and renderer-aware coordination for the UI assertion.

Check your solution

  • Unchanged reads are stable and both listeners see the first update.
  • After A cleanup only B sees the next update.

Key takeaways

  • Subscriptions need symmetric cleanup.
  • Unchanged snapshots must retain their identity.
  • Match initial server and hydration data without sharing private request state.
  • Unchanged store data must yield the same snapshot value under Object.is.
  • Publish a new immutable snapshot before notifying and remove the exact subscribed callback.
  • Server snapshot consistency does not replace authorization or request isolation.

Official references