AceDevHub
Advanced React Interview QuestionsAdvancedConcept

React · Question 84

Why does React provide useSyncExternalStore instead of recommending a normal Effect subscription for external stores?

Direct answer

useSyncExternalStore gives React a consistent snapshot-and-subscribe contract for mutable data outside React, including correct integration with concurrent rendering and server rendering.

useOnlineStatus.js
function useOnlineStatus() {
  return useSyncExternalStore(
    subscribe,
    getSnapshot,
    getServerSnapshot
  );
}

function getSnapshot() {
  return navigator.onLine;
}

function subscribe(callback) {
  window.addEventListener("online", callback);
  window.addEventListener("offline", callback);

  return () => {
    window.removeEventListener("online", callback);
    window.removeEventListener("offline", callback);
  };
}
  • subscribe: tells React how to listen for store changes and clean up.
  • getSnapshot: returns the current immutable snapshot React should render.
  • getServerSnapshot: optionally provides the initial server/hydration snapshot.