What is the useSyncExternalStore hook?
Answer
useSyncExternalStore (React 18) is the recommended hook for subscribing to external data stores in a way that is compatible with concurrent rendering. External stores include browser APIs (window.innerWidth, navigator.online), third-party state libraries (Zustand, Redux), and any mutable external value. Signature: const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?);. subscribe: a function that registers a listener and returns an unsubscribe function. getSnapshot: a function that returns the current value (must return the same value if nothing changed). getServerSnapshot: for SSR, returns the server-side snapshot. Example: const isOnline = useSyncExternalStore(window.addEventListener.bind(window, "online"), () => navigator.onLine);. Why not useState + useEffect for subscriptions: in concurrent mode, useEffect fires asynchronously and can miss updates that happen between render and the effect. useSyncExternalStore provides "tear-free" reads — the snapshot is always consistent with what was rendered. Redux Toolkit and Zustand use this hook internally.