Zustand is a popular lightweight state management library that uses an external store. Here’s how you can integrate it with useSyncExternalStore:
javascript
import { createStore } from 'zustand';
import { useSyncExternalStore } from 'react';
// 1. Create a Zustand store
const store = createStore((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
// 2. Define subscription and snapshot functions
const subscribe = (callback) => {
const unsubscribe = store.subscribe(callback);
return unsubscribe; // Cleanup function
};
const getSnapshot = () => store.getState();
// 3. Create a custom hook
function useZustandStore() {
return useSyncExternalStore(subscribe, getSnapshot);
}
// 4. Use in a React component
function Counter() {
const { count, increment, decrement } = useZustandStore();
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
}
Key Takeaways:
Zustand already provides a subscription mechanism (store.subscribe), which we use in subscribe.
getSnapshot simply returns the current state using store.getState().
The custom hook useZustandStore ensures React re-renders when the store updates.
2. With a Non-React State System (Class-Based Store)
Suppose you have a legacy class-based state system (e.g., a singleton store or an event-driven state manager). Here’s how to integrate it with React using useSyncExternalStore:
The CounterStore class manages its own state and notifies listeners when changes occur.
subscribe connects React to the store’s event system.
getSnapshot provides the latest state to React.
The custom hook useCounterStore ensures React re-renders when the store updates.
Comparison of Both Approaches
Feature
Zustand (State Management Library)
Class-Based Store
Subscription
Uses store.subscribe
Custom subscribe method
Snapshot
Uses store.getState
Custom getState method
State Updates
Uses Zustand’s set function
Manual increment/decrement
Cleanup
Automatically handled by Zustand
Manually managed in subscribe
Boilerplate
Minimal (Zustand handles it)
More manual setup
When to Use useSyncExternalStore
✅ When integrating with external state (Redux, MobX, RxJS, browser APIs).
✅ When working with legacy or non-React state systems (class-based stores, singletons).
✅ When you need SSR support (via getServerSnapshot).
🚫 Not needed for React’s built-in state (useState, useReducer, useContext).
Final Thoughts
useSyncExternalStore is essential for safely integrating external stores with React 18+.
It prevents tearing (inconsistent UI state) in concurrent mode.
Works seamlessly with both modern state libraries and legacy systems.
Would you like a deeper dive into SSR support (getServerSnapshot) or performance optimizations? 🚀