Category: react
What Is useSyncExternalStore?
Published on 27 Oct 2026
Explanation
useSyncExternalStore lets a component subscribe to a store that exists outside React, using a subscription function and a snapshot-reading function. It is useful for integrating external state sources safely.
Code:
const value = useSyncExternalStore( store.subscribe, store.getSnapshot );
Explanation
The store should notify subscribers whenever its snapshot changes. The snapshot must be stable when the underlying data has not changed.
Code:
const listeners = new Set();
let count = 0;
const store = {
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
getSnapshot() {
return count;
},
increment() {
count += 1;
listeners.forEach((listener) => listener());
}
};
Explanation
Pass the store's subscribe and getSnapshot methods to useSyncExternalStore. When the store notifies subscribers and the snapshot changes, React rerenders the component with the new value.
Code:
function Counter() {
const count = useSyncExternalStore(store.subscribe, store.getSnapshot);
return <button onClick={store.increment}>Count: {count}</button>;
}
Explanation
For server-rendered applications, provide getServerSnapshot when needed so the server and initial client render can use a matching snapshot. This helps avoid hydration mismatches.
Code:
const value = useSyncExternalStore( store.subscribe, store.getSnapshot, store.getServerSnapshot );
Explanation
getSnapshot should return the same value by identity while the store has not changed. Returning a freshly created object on every call can cause repeated renders or React warnings; cache object snapshots when necessary.
Code:
let snapshot = { count: 0 };
function getSnapshot() {
return snapshot;
}
function updateCount(count) {
snapshot = { count }; // Replace only when data changes
listeners.forEach((listener) => listener());
}