Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(web): keep the localStorage preference updater pure (#17006)

Nikita Kabardina646c24993d2
diff --git a/web/src/components/useLocalStorage.clienttest.tsx b/web/src/components/useLocalStorage.clienttest.tsx
index 1017d9df29..16ed22777c 100644
--- a/web/src/components/useLocalStorage.clienttest.tsx
+++ b/web/src/components/useLocalStorage.clienttest.tsx
@@ -1,8 +1,25 @@
-import { act, renderHook } from "@testing-library/react";
+import { act, render, renderHook, screen } from "@testing-library/react";
+import { useEffect } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import useLocalStorage from "@/src/components/useLocalStorage";
+const SHARED_KEY = "test-shared-pref-key";
+
+/**
+ * One component holding the shared preference. Two of these side by side is the
+ * real shape: a page and a panel inside it both read the same key.
+ */
+const Subscriber = ({
+ register,
+}: {
+ register?: (setValue: (value: string) => void) => void;
+}) => {
+ const [value, setValue] = useLocalStorage(SHARED_KEY, "initial");
+ useEffect(() => register?.(setValue), [register, setValue]);
+ return <span>{value}</span>;
+};
+
// Seam contract for preference persistence: a localStorage write that throws
// (quota exceeded, Safari private mode) must not propagate an exception and
// must not log at error level — the Sentry console integration turns
@@ -53,4 +70,33 @@ describe("useLocalStorage", () => {
expect(warnSpy).toHaveBeenCalled();
expect(errorSpy).not.toHaveBeenCalled();
});
+
+ // Two instances of the key on one page: setting it from one must reach the
+ // other WITHOUT setting state on it mid-render. React runs a state updater
+ // during the render phase, so a side effect in there (the same-tab notify)
+ // updates every other subscriber while a component is rendering — benign as
+ // a warning, and one dependency away from an update loop.
+ it("reaches the other instances of the key without updating them during a render", () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ let setFromFirst: ((value: string) => void) | undefined;
+
+ render(
+ <>
+ <Subscriber register={(setValue) => (setFromFirst = setValue)} />
+ <Subscriber />
+ </>,
+ );
+
+ // Two writes in one batch, because React evaluates a lone updater eagerly
+ // (outside the render phase) to check for a bail-out. With an update
+ // already queued it runs the updater during the render instead — which is
+ // what a real interaction does, where the same click also moves other state.
+ act(() => {
+ setFromFirst?.("first");
+ setFromFirst?.("updated");
+ });
+
+ expect(screen.getAllByText("updated")).toHaveLength(2);
+ expect(errorSpy).not.toHaveBeenCalled();
+ });
});
diff --git a/web/src/components/useLocalStorage.tsx b/web/src/components/useLocalStorage.tsx
index 33a1e4e363..1464211106 100644
--- a/web/src/components/useLocalStorage.tsx
+++ b/web/src/components/useLocalStorage.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useMemo } from "react";
+import { useState, useEffect, useCallback, useMemo, useRef } from "react";
/**
* useLocalStorage is a hook for managing data with the localStorage API.
@@ -76,10 +76,29 @@ function useLocalStorage<T>(
setValue(initialValue);
};
- // Sync to localStorage whenever value changes
- // This ensures localStorage always has the latest value
+ // Whether the current value came from this instance's own setter, and so is
+ // the one the other instances in this tab still have to be told about. A
+ // value that arrived FROM one of them is never re-announced.
+ const isOwnWriteRef = useRef(false);
+
+ // Sync to localStorage whenever value changes, and — for a value this
+ // instance set itself — notify the other instances in this tab.
+ //
+ // Both are side effects, so they run here and never inside the state
+ // updater. React invokes an updater during the render phase (and twice in
+ // StrictMode), so dispatching from there calls setState on every other
+ // subscriber to this key while a component is rendering: React's "Cannot
+ // update a component while rendering a different component".
useEffect(() => {
- safeLocalStorage.set(value);
+ const stringified = safeLocalStorage.set(value);
+ if (!isOwnWriteRef.current) return;
+ isOwnWriteRef.current = false;
+ if (stringified === null) return;
+ window.dispatchEvent(
+ new CustomEvent("localStorageChange", {
+ detail: { key: localStorageKey, newValue: stringified },
+ }),
+ );
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [localStorageKey, value]);
@@ -91,6 +110,7 @@ function useLocalStorage<T>(
const handleStorageChange = (e: StorageEvent) => {
if (e.key === localStorageKey) {
try {
+ isOwnWriteRef.current = false;
setValue(e.newValue ? (JSON.parse(e.newValue) as T) : initialValue);
} catch (error) {
console.warn("Error parsing storage change", error);
@@ -104,6 +124,7 @@ function useLocalStorage<T>(
) => {
if (e.detail.key === localStorageKey) {
try {
+ isOwnWriteRef.current = false;
setValue(
e.detail.newValue
? (JSON.parse(e.detail.newValue) as T)
@@ -132,30 +153,14 @@ function useLocalStorage<T>(
};
}, [localStorageKey, initialValue]);
- // Enhanced setValue function that also notifies other tabs
+ // Enhanced setValue that also persists and notifies the other instances in
+ // this tab — from the effect above, so this stays a plain state update and
+ // the updater React runs stays pure. Updater functions pass straight through.
const setValueAndNotify: React.Dispatch<React.SetStateAction<T>> =
- useCallback(
- (newValue) => {
- setValue((prev) => {
- // Handle both direct values and updater functions
- const resolvedValue =
- newValue instanceof Function ? newValue(prev) : newValue;
- const stringified = safeLocalStorage.set(resolvedValue);
-
- // Dispatch custom event to notify other instances in the same tab
- if (stringified) {
- window.dispatchEvent(
- new CustomEvent("localStorageChange", {
- detail: { key: localStorageKey, newValue: stringified },
- }),
- );
- }
-
- return resolvedValue;
- });
- },
- [localStorageKey, safeLocalStorage],
- );
+ useCallback((newValue) => {
+ isOwnWriteRef.current = true;
+ setValue(newValue);
+ }, []);
return [value, setValueAndNotify, clearValue] as const;
}