The best way to control Claude Code, Codex and more from any computer or phone
perf: debounce Zustand store persistence and deduplicate legacy cleanup
The useStore subscriber called persistState on every state mutation, triggering JSON.stringify + localStorage.setItem synchronously. It also ran 8 localStorage.removeItem calls for legacy keys on every fire. Wrap the subscriber with a 500ms debounce so rapid state changes batch into a single write. Move legacy key cleanup behind a one-time flag so it runs only once per page load. Add a beforeunload handler to flush the final state.
Chukwudi Nwobodo committed
Mar 8, 2026 at 06:22 UTC
7a377fc5e4d607a475a7d36957689562d5dcccb9
1 file changed
+32
-4
apps/web/src/store.ts
+32
-4
@@ -63,6 +63,8 @@ function readPersistedState(): AppState {
63
}
64
}
65
66
+let legacyKeysCleanedUp = false;
67
+
68
function persistState(state: AppState): void {
69
if (typeof window === "undefined") return;
70
try {
@@ -74,14 +76,29 @@ function persistState(state: AppState): void {
76
.map((project) => project.cwd),
77
}),
78
);
77
- for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
78
- window.localStorage.removeItem(legacyKey);
79
+ if (!legacyKeysCleanedUp) {
80
+ legacyKeysCleanedUp = true;
81
+ for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
82
+ window.localStorage.removeItem(legacyKey);
83
+ }
84
}
85
} catch {
86
// Ignore quota/storage errors to avoid breaking chat UX.
87
}
88
}
89
90
+let persistTimer: ReturnType<typeof setTimeout> | null = null;
91
+
92
+function debouncedPersistState(state: AppState): void {
93
+ if (persistTimer !== null) {
94
+ clearTimeout(persistTimer);
95
+ }
96
+ persistTimer = setTimeout(() => {
97
+ persistTimer = null;
98
+ persistState(state);
99
+ }, 500);
100
+}
101
+
102
// ── Pure helpers ──────────────────────────────────────────────────────
103
104
function updateThread(
@@ -395,8 +412,19 @@ export const useStore = create<AppStore>((set) => ({
412
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
413
}));
414
398
-// Persist on every state change
399
-useStore.subscribe((state) => persistState(state));
415
+// Persist state changes with debouncing to avoid localStorage thrashing
416
+useStore.subscribe((state) => debouncedPersistState(state));
417
+
418
+// Flush pending writes synchronously before page unload to prevent data loss.
419
+if (typeof window !== "undefined") {
420
+ window.addEventListener("beforeunload", () => {
421
+ if (persistTimer !== null) {
422
+ clearTimeout(persistTimer);
423
+ persistTimer = null;
424
+ persistState(useStore.getState());
425
+ }
426
+ });
427
+}
428
429
export function StoreProvider({ children }: { children: ReactNode }) {
430
useEffect(() => {