Intermediate LevelReact JS & React 19
What is useSyncExternalStore and why do Redux and Zustand rely on it?
❓ Interview Prompt: Explain `useSyncExternalStore`, tearing prevention in concurrent rendering, subscribing to external non-React stores, and state hydration.
'useSyncExternalStore' is a hook recommended for reading and subscribing from external non-React data stores (Redux, Zustand, browser APIs):
Why It Was Added (React 18):
In Concurrent React, rendering can pause and yield control to the browser. If an external store updates mid-render, different components read different data versions (Tearing!). 'useSyncExternalStore' guarantees synchronous reads, eliminating visual tearing completely.
Code Implementation Example
jsx
import { useSyncExternalStore } from 'react';
// Custom hook subscribing to browser online/offline status
function useOnlineStatus() {
const isOnline = useSyncExternalStore(
(callback) => {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
},
() => navigator.onLine, // Client snapshot
() => true // Server snapshot for SSR
);
return isOnline;
}💡Subscribing to browser online status using useSyncExternalStore.
🎯 Interview Key Takeaway
Use useSyncExternalStore when integrating external non-React state stores to prevent tearing in Concurrent React.
#useSyncExternalStore#State Management#Redux#Zustand#Intermediate
Back to all React JS & React 19 Questions→