useSyncExternalStore
Definition
`useSyncExternalStore` is a React Hook that lets you subscribe to an external store in a way that is compatible with concurrent rendering features.
Explain Like I'm New
React normally likes to be the boss of all the data (State). But sometimes, data lives completely outside of React (like the browser's `navigator.onLine` status, or a 3rd-party library like Redux). If React tries to read this outside data while doing its new fast 'Concurrent' rendering, it can get confused and show different data on the screen at the same time (tearing). `useSyncExternalStore` is a special bridge that guarantees React safely reads outside data without visual glitches.
Real World Example
Zustand and Redux both use `useSyncExternalStore` heavily under the hood in React 18 to ensure their global stores sync perfectly with React components.
Common Use Cases
- •Subscribing to browser APIs (like window.innerWidth, online/offline status)
- •Building Global State Management libraries (Redux, Zustand, MobX)
- •Preventing 'Tearing' in UI during Concurrent Rendering
Interactive Example
import { useSyncExternalStore } from 'react'; // 1. We create a subscription function for a browser API (External Store) function subscribe(callback) { window.addEventListener('online', callback); window.addEventListener('offline', callback); // Cleanup function return () => { window.removeEventListener('online', callback); window.removeEventListener('offline', callback); }; } // 2. We create a function to get the current snapshot of the data function getSnapshot() { return navigator.onLine; } export default function NetworkStatus() { // 3. We use the hook! // React will automatically re-render this component if the snapshot changes. const isOnline = useSyncExternalStore(subscribe, getSnapshot); return ( <div> <h2>System Status</h2> <p>You are currently: <b>{isOnline ? '🟢 Online' : '🔴 Offline'}</b></p> </div> ); }
Interview Questions
basic
- What is an 'external store' in the context of React?
- Why was `useSyncExternalStore` introduced in React 18?
intermediate
- What are the two required arguments for `useSyncExternalStore`?
- What is 'Tearing' in UI rendering?
advanced
- Why is `useEffect` + `useState` not recommended for subscribing to external stores anymore?
- What does the third (optional) `getServerSnapshot` argument do?
trick
- Is `useSyncExternalStore` intended to replace `useState` for normal component logic?