Skip to article content
FrontendXLesson 17 / 40

External Stores with useSyncExternalStore

Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.

advanced · about 55 minutes · 4 exercises

  • Predict
  • Implement
  • Debug
  • Interview

What you will be able to do

#
  • Subscribe a component to state owned outside React.
  • Return a stable snapshot and explain why it matters.
  • Explain tearing and how the hook prevents it.

Overview

#

State that lives outside React

Some state is owned by something other than React: a browser API, a global store, a WebSocket, or a third-party library. useSyncExternalStore lets a component subscribe to such a store and read a consistent snapshot during render.

snippet.tsx
const isOnline = useSyncExternalStore(
  (cb) => {
    window.addEventListener('online', cb);
    window.addEventListener('offline', cb);
    return () => {
      window.removeEventListener('online', cb);
      window.removeEventListener('offline', cb);
    };
  },
  () => navigator.onLine,
);

The first argument subscribes and returns an unsubscribe. The second reads the current snapshot. The third, optional, returns the snapshot for server rendering.

Snapshots must be stable

getSnapshot must return the same value until the store actually changes. Returning a new object every call makes React re-render forever, because React compares the snapshot by reference. Cache the object in the store and return the same reference until an update.

snippet.tsx
// wrong: a new object each call
() => ({ count: store.count })

// right: a cached reference the store updates on change
() => store.snapshot

Tearing and consistency

useSyncExternalStore reads the snapshot during render and checks it again after commit. If the store changed mid-render, React re-renders so every component sees the same value. This avoids tearing, where two components read different values of the same store in one frame.

Pitfall: subscribing on every render

The subscribe function should be stable, or memoized, otherwise React resubscribes on every render. Define it outside the component or wrap it in useCallback.

When to use it

Use it for genuinely external state or to build a store library. For state React already owns, useState, useReducer and context are simpler.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What happens if getSnapshot returns a new object every call?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.tsx
    useSyncExternalStore(subscribe, () => ({ count: store.count }));
    Choose the best answer
  2. Exercise 2Implement

    Implement a hook that subscribes to a simple external counter store and returns its value.

    starter.tsx
    const store = {
      value: 0,
      listeners: new Set<() => void>(),
      subscribe(cb: () => void) { this.listeners.add(cb); return () => this.listeners.delete(cb); },
      getSnapshot() { return this.value; },
    };
    
    export function useCounter() {
      return 0;
    }

    Reveal the reference answer
    reference.tsx
    import { useSyncExternalStore } from 'react';
    
    export function useCounter() {
      return useSyncExternalStore(
        (cb) => store.subscribe(cb),
        () => store.getSnapshot(),
      );
    }

    Authored expected output: The hook returns the current store value and re-renders when the store notifies listeners.

    The subscribe function returns the store's unsubscribe, and getSnapshot returns the primitive value, which is stable until it changes. React re-renders the component when the store calls the listener.

  3. Exercise 3Debug

    This component resubscribes on every render and reads an unstable snapshot. Explain and fix both.

    starter.tsx
    function Status() {
      const timeRef = useRef(Date.now());
      const value = useSyncExternalStore(
        (cb) => {
          const id = setInterval(() => {
            timeRef.current = Date.now();
            cb();
          }, 1000);
          return () => clearInterval(id);
        },
        () => timeRef.current,
      );
      return <p>{value}</p>;
    }

    Reveal the reference answer
    reference.tsx
    function Status() {
      const timeRef = useRef(Date.now());
      const subscribe = useCallback((cb: () => void) => {
        const id = setInterval(() => {
          timeRef.current = Date.now();
          cb();
        }, 1000);
        return () => clearInterval(id);
      }, []);
      const value = useSyncExternalStore(subscribe, () => timeRef.current);
      return <p>{value}</p>;
    }

    Authored expected output: The subscription is created once and cleaned up on unmount, and the cached snapshot avoids a re-render loop.

    Two problems must be fixed. An inline subscribe function is a new reference on each render, so React tears down and recreates the subscription every time; useCallback gives it a stable identity. Also, getSnapshot must return a cached value that changes only when the store actually updates: the original () => Date.now() returns a new value on every read, which React treats as a constant change and re-renders in a loop. Reading a cached ref and updating it before calling cb makes the snapshot stable between updates.

  4. Exercise 4Interview

    Explain what tearing is and how useSyncExternalStore prevents it.

    starter.tsx
    // two components reading the same external store

    Reveal the reference answer
    reference.tsx
    Tearing is when two components in the same commit read different values from one store, so the UI is inconsistent. It can happen with external stores because React cannot know when they change. useSyncExternalStore reads the snapshot during render and re-checks it after commit; if the store changed in between, React re-renders so every component reads the same value. This keeps a single consistent snapshot per commit.

    Authored expected output: A written explanation of inconsistent reads and the render-then-verify mechanism.

    The guarantee is consistency across a commit, not freshness at every instant. React verifies the snapshot after commit and re-renders if it moved.

Common misconceptions

#
  • useSyncExternalStore is for all global state. It is for state owned outside React; React state uses useState or context.
  • getSnapshot may build a new object each call. It must return a stable reference or React loops.
  • The subscribe function can be recreated each render. An unstable subscribe causes constant resubscription.
  • Server rendering does not apply. The optional third argument supplies the server snapshot.

Follow-up practice

#
  • react-context-performance
  • react-data-fetching-caches

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.