MyInternships.in

React Hooks

React useSyncExternalStore Hook

useSyncExternalStore subscribes a component to a store that lives outside React — a Redux store, a browser API, a plain event emitter — in a way that is safe under concurrent rendering and server-side rendering.


What is useSyncExternalStore Hook in React?

useSyncExternalStore subscribes a component to a store that lives outside React — a Redux store, a browser API, a plain event emitter — in a way that is safe under concurrent rendering and server-side rendering.

Why useSyncExternalStore Hook matters

Subscribing with useEffect can show a torn UI: two components reading the same store during one render can see different values. This hook guarantees every component in a render sees the same snapshot.

useSyncExternalStore Hook example

Tracking the browser online status
JSX
function subscribe(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

function useOnlineStatus() {
  return useSyncExternalStore(
    subscribe,
    () => navigator.onLine,   // client snapshot
    () => true                // server snapshot
  );
}

How this works

subscribe registers a listener and returns its cleanup. The second argument reads the current value; the third supplies a value during server rendering, where navigator does not exist.

Key points to remember

  • The snapshot function must return a cached value — returning a new object each call causes an infinite loop.
  • State libraries such as Redux and Zustand use this hook internally.
  • Most application code never calls it directly.

Common mistakes with useSyncExternalStore Hook

  • Returning a freshly built object from getSnapshot, which React detects as a change every time.
  • Omitting the server snapshot in a server-rendered app, causing a hydration error.

React useSyncExternalStore Hook— Interview Questions & FAQs

Do I need useSyncExternalStore in normal app code?+

Rarely. It exists for library authors and for subscribing to browser APIs. If you use Redux Toolkit or Zustand, they already call it for you.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships