Skip to content

Commit df4ea2f

Browse files
Merge pull request #513 from Meet-hybrid/feature/batch-zustand-mutations
feat: add zustandBatch utility for batching state updates in React Native
2 parents c595d9a + b52b8b2 commit df4ea2f

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

src/utils/zustandBatch.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+

0 commit comments

Comments
 (0)