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.
This commit is contained in:
Chukwudi Nwobodo committed 2026-03-08 06:22:02 +00:00
1 parent e21687300e
commit dd51d4faec
1 file changed
+32 -4
+32 -4
View File
@@ -62,6 +62,8 @@ function readPersistedState(): AppState {
}
}
let legacyKeysCleanedUp = false;
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
@@ -73,14 +75,29 @@ function persistState(state: AppState): void {
.map((project) => project.cwd),
}),
);
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
if (!legacyKeysCleanedUp) {
legacyKeysCleanedUp = true;
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
let persistTimer: ReturnType<typeof setTimeout> | null = null;
function debouncedPersistState(state: AppState): void {
if (persistTimer !== null) {
clearTimeout(persistTimer);
}
persistTimer = setTimeout(() => {
persistTimer = null;
persistState(state);
}, 500);
}
// ── Pure helpers ──────────────────────────────────────────────────────
function updateThread(
@@ -394,8 +411,19 @@ export const useStore = create<AppStore>((set) => ({
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
}));
// Persist on every state change
useStore.subscribe((state) => persistState(state));
// Persist state changes with debouncing to avoid localStorage thrashing
useStore.subscribe((state) => debouncedPersistState(state));
// Flush pending writes synchronously before page unload to prevent data loss.
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
if (persistTimer !== null) {
clearTimeout(persistTimer);
persistTimer = null;
persistState(useStore.getState());
}
});
}
export function StoreProvider({ children }: { children: ReactNode }) {
useEffect(() => {