File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // React Native environment typically provides unstable_batchedUpdates via react-native.
2+ // In case typings are unavailable, we fall back to the global React batching.
3+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4+ const unstable_batchedUpdates : ( ( fn : ( ) => void ) => void ) | undefined = ( globalThis as any )
5+ ?. unstable_batchedUpdates ;
6+
7+ /**
8+ * Batch multiple Zustand `setState` calls (or any state work) into a single
9+ * React render pass.
10+ *
11+ * Usage:
12+ * ```ts
13+ * import { batch } from '@/utils/zustandBatch';
14+ *
15+ * batch(() => {
16+ * store.getState().setName('...');
17+ * store.getState().setAvatar('...');
18+ * });
19+ * ```
20+ *
21+ * Why:
22+ * React Native can still schedule multiple renders if updates happen in
23+ * separate ticks / microtasks. `unstable_batchedUpdates` forces them to land
24+ * together.
25+ */
26+ export function batch ( fn : ( ) => void ) : void {
27+ if ( typeof unstable_batchedUpdates === 'function' ) {
28+ unstable_batchedUpdates ( fn ) ;
29+ return ;
30+ }
31+
32+ // Fallback: single execution (best-effort). Zustand often batches sync calls
33+ // even without unstable_batchedUpdates.
34+ fn ( ) ;
35+ }
36+
37+
You can’t perform that action at this time.
0 commit comments