Interview frequency: …
Short answer
It subscribes to external stores synchronously to prevent Tearing when data changes while an interruptible Concurrent Rendering update is underway.
Explanation
In Concurrent Mode, React can interrupt rendering and resume it later. If an external data source (such as Redux or window.history) changes during the interruption, some components may show the old value while others show the new value on the same screen. This is called Tearing. The Hook guarantees a consistent, atomic read.
Code example
import { useSyncExternalStore } from 'react';
function subscribe(callback: () => void) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine,
() => true // The default value on the server during SSR
);
}Common mistakes
- Returning a new object every time from getSnapshot, causing the component to render in an infinite loop.