Absolutely! Let's walk through two concrete, real-world examples that illustrate how to effectively use useSyncExternalStore:
✅ 1. With a State Management Library (Zustand)
💡 Use Case:
Using Zustand (a popular state management library) in a way that’s fully concurrent-safe and works correctly with React 18+ features like concurrent rendering or React Server Components (RSC).
⚠️ Problem:
Prior versions of Zustand used internal subscription mechanisms that were not concurrency-aware. Now, Zustand supports useSyncExternalStore natively for this reason.
🧪 Example – Zustand Store
// store.js
import { createStore } from 'zustand/vanilla'
// ✅ Concurrent-safe vanilla store outside of React
export const counterStore = createStore(() => ({
count: 0,
increment: () => counterStore.setState((s) => ({ count: s.count + 1 })),
}))
✅ React Integration with useSyncExternalStore
You can now use useSyncExternalStore to safely subscribe to the store:
// useCounter.ts (custom hook using useSyncExternalStore)
import { useSyncExternalStore } from 'react'
import { counterStore } from './store'
// Safe, concurrent-ready selector hook
export function useCounter() {
return useSyncExternalStore(
counterStore.subscribe, // 🔔 Subscribe to updates
() => counterStore.getState(), // 📦 Get current state
() => counterStore.getState() // 👻 For SSR – same fallback
)
}
🔁 Usage in a Component
// Counter.tsx
import { useCounter } from './useCounter'
import { counterStore } from './store'
export default function Counter() {
const state = useCounter()
return (
<div>
<p>Count: {state.count}</p>
<button onClick={counterStore.getState().increment}>Increment</button>
</div>
)
}
✅ Benefits:
- No tearing – shows correct state in concurrent mode.
- Works with SSR and hydration.
- Uses Zustand’s efficient minimal reactivity but integrates tightly with React.
✅ 2. With a Non-React State System (Vanilla Class Store)
💡 Use Case:
Imagine you're working in a large legacy app or integrated system that uses plain JavaScript classes or a custom event emitter-based state system outside React.
🧱 Example – Custom Class-Based Store
// counterClassStore.js
class CounterStore {
count = 0
listeners = new Set()
getSnapshot = () => ({ count: this.count })
subscribe = (callback) => {
this.listeners.add(callback)
return () => this.listeners.delete(callback)
}
increment = () => {
this.count++
this.emit()
}
emit = () => {
this.listeners.forEach((listener) => listener())
}
}
export const counterClassStore = new CounterStore()
✅ React Hook Using useSyncExternalStore
// useClassCounter.ts
import { useSyncExternalStore } from 'react'
import { counterClassStore } from './counterClassStore'
export function useClassCounter() {
return useSyncExternalStore(
counterClassStore.subscribe,
counterClassStore.getSnapshot,
counterClassStore.getSnapshot // SSR snapshot (same here)
)
}
🔁 Usage in a Component
// CounterClassComponent.tsx
import { useClassCounter } from './useClassCounter'
import { counterClassStore } from './counterClassStore'
export default function CounterClassComponent() {
const state = useClassCounter()
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => counterClassStore.increment()}>Increment</button>
</div>
)
}
✅ Benefits with useSyncExternalStore:
- Your class-based store becomes concurrent-mode safe.
- Supports React 18+ features like Suspense, RSC and more.
- Removes race conditions or stale renders from old subscription models.
🤔 Summary
| Feature | Zustand Example | Class Store Example |
|---|
| Concurrent Mode Support | ✅ Yes | ✅ Yes |
| SSR support (optional param) | ✅ | ✅ |
| Custom Event/System | ❌ | ✅ |
| State Selector Support | ✅ Zustand supports useStore((s) => s.value) | 🚫 Not in base class (you'd have to add it) |
🧠 Fun Idea – Generic Hook for Any External Store
You can write a generic utility for safer store integration:
function createStoreHook(store) {
return function useStoreSelector(selector) {
return useSyncExternalStore(
store.subscribe,
() => selector(store.getSnapshot()),
() => selector(store.getSnapshot())
)
}
}
Then use:
const useCount = createStoreHook(counterClassStore)
🔚 Wrap-Up
useSyncExternalStore 🔗 React to any external system:
- Works with Redux, Zustand, MobX (when integrated properly).
- Works with custom event emitters, RxJS, or old-school class systems.
This hook ensures you never render stale state, and works seamlessly with React's modern features.
Let me know if you’d like examples with:
- Redux (modern setup)
- RxJS Observables
- WebSocket stores
- Browser APIs like
localStorage or matchMedia