Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

perf: reuse frontend lookups and lazily initialize values (#11375)

Myles Scolnick6d839e48db13
diff --git a/frontend/src/components/app-config/ai-config.tsx b/frontend/src/components/app-config/ai-config.tsx
index 6130c9ec2b..b208ffc81a 100644
--- a/frontend/src/components/app-config/ai-config.tsx
+++ b/frontend/src/components/app-config/ai-config.tsx
@@ -48,6 +48,7 @@ import { DEFAULT_AI_MODEL, type UserConfig } from "@/core/config/config-schema";
import { isWasm } from "@/core/wasm/utils";
import { cn } from "@/utils/cn";
import { Events } from "@/utils/events";
+import { Objects } from "@/utils/objects";
import { Strings } from "@/utils/strings";
import { AIModelDropdown, getProviderLabel } from "../ai/ai-model-dropdown";
import {
@@ -681,7 +682,10 @@ export const CustomProvidersConfig: React.FC<AiConfigProps> = ({
};
const removeProvider = (providerName: string) => {
- const { [providerName]: _, ...rest } = customProviders;
+ const rest = Objects.filter(
+ customProviders,
+ (_, name) => name !== providerName,
+ );
// Reset to clear nested dirty state, then set new value
form.resetField("ai.custom_providers");
form.setValue("ai.custom_providers", rest, { shouldDirty: true });
diff --git a/frontend/src/components/data-table/__tests__/date-popover.test.tsx b/frontend/src/components/data-table/__tests__/date-popover.test.tsx
new file mode 100644
index 0000000000..7e18acc985
--- /dev/null
+++ b/frontend/src/components/data-table/__tests__/date-popover.test.tsx
@@ -0,0 +1,72 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { I18nProvider } from "react-aria";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { DatePopover } from "../date-popover";
+
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ content }: { content: ReactNode }) => content,
+}));
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("DatePopover", () => {
+ it.each([0, 123])(
+ "updates the local timezone and time on rerender with %i milliseconds",
+ (milliseconds) => {
+ const NativeDateTimeFormat = Intl.DateTimeFormat;
+ let systemTimezone = "America/Los_Angeles";
+ vi.spyOn(Intl, "DateTimeFormat").mockImplementation(
+ function (locales, options) {
+ return new NativeDateTimeFormat(locales, {
+ ...options,
+ timeZone: options?.timeZone ?? systemTimezone,
+ });
+ },
+ );
+
+ const date = new Date("2026-01-15T12:00:00Z");
+ date.setUTCMilliseconds(milliseconds);
+ const content = () => (
+ <I18nProvider locale="en-US">
+ <DatePopover date={date} type="datetime">
+ timestamp
+ </DatePopover>
+ </I18nProvider>
+ );
+ const { rerender } = render(content());
+ const previousTime =
+ screen.getByText(systemTimezone).nextElementSibling?.textContent;
+ const utcTime = screen.getByText("UTC").nextElementSibling?.textContent;
+
+ systemTimezone = "Asia/Tokyo";
+ rerender(content());
+
+ const expected = new NativeDateTimeFormat("en-US", {
+ timeZone: systemTimezone,
+ ...(milliseconds
+ ? {
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ fractionalSecondDigits: 3,
+ }
+ : { dateStyle: "long", timeStyle: "medium" }),
+ }).format(date);
+ expect(screen.queryByText("America/Los_Angeles")).toBeNull();
+ expect(
+ screen.getByText(systemTimezone).nextElementSibling?.textContent,
+ ).toBe(expected);
+ expect(expected).not.toBe(previousTime);
+ expect(screen.getByText("UTC").nextElementSibling?.textContent).toBe(
+ utcTime,
+ );
+ },
+ );
+});
diff --git a/frontend/src/components/data-table/column-visibility-dropdown.tsx b/frontend/src/components/data-table/column-visibility-dropdown.tsx
index a2362dca72..7ad535445b 100644
--- a/frontend/src/components/data-table/column-visibility-dropdown.tsx
+++ b/frontend/src/components/data-table/column-visibility-dropdown.tsx
@@ -6,7 +6,7 @@
import type { Table } from "@tanstack/react-table";
import { Columns3Icon, EyeIcon, EyeOffIcon, ScanEyeIcon } from "lucide-react";
-import React, { useMemo } from "react";
+import React from "react";
import { ColumnName } from "@/components/datasources/components";
import { Button } from "@/components/ui/button";
import {
@@ -24,6 +24,7 @@ import {
} from "@/components/ui/popover";
import { type BulkAction, useSelectList } from "@/components/ui/select-core";
import type { DataType } from "@/core/kernel/messages";
+import { Arrays } from "@/utils/arrays";
import { cn } from "@/utils/cn";
import { Events } from "@/utils/events";
import { smartMatchFilter } from "@/utils/smartMatch";
@@ -67,9 +68,8 @@ export const ColumnVisibilityDropdown = <TData,>({
const hideableIds = userColumns
.filter((column) => column.getCanHide())
.map((column) => column.id);
- const visibleHideableCount = hideableIds.filter(
- (id) => !hiddenIds.includes(id),
- ).length;
+ const visibleHideableColumnIds = Arrays.difference(hideableIds, hiddenIds);
+ const visibleHideableCount = visibleHideableColumnIds.length;
const applyHidden = (next: string[] | string | null) => {
const hidden = new Set(Array.isArray(next) ? next : []);
@@ -106,15 +106,10 @@ export const ColumnVisibilityDropdown = <TData,>({
.filter((option) => !option.disabled)
.map((option) => option.value)
: [];
- const showOnlyColumnState = useMemo(
- () => ({
- visibleHideableColumnIds: hideableIds.filter(
- (id) => !hiddenIds.includes(id),
- ),
- hideableColumnIdSet: new Set(hideableIds),
- }),
- [hideableIds, hiddenIds],
- );
+ const showOnlyColumnState = {
+ visibleHideableColumnIds,
+ hideableColumnIdSet: new Set(hideableIds),
+ };
const hasSearchBulkActions =
showOnlyMatchIds.length > 0 || matchingActions.length > 0;
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index ff2e8b4fe2..6c3ab4c253 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -135,6 +135,7 @@ export function generateColumns<T>({
}): ColumnDef<T>[] {
// Row-headers are typically index columns
const rowHeadersSet = new Set(rowHeaders.map(([columnName]) => columnName));
+ const wrappedColumnsSet = new Set(wrappedColumns);
const typesByColumn = Maps.keyBy(fieldTypes, (entry) => entry[0]);
@@ -287,7 +288,7 @@ export function generateColumns<T>({
}
const justify = getJustify(key);
- const wrapped = wrappedColumns?.includes(key);
+ const wrapped = wrappedColumnsSet.has(key);
const isCellSelected = cell?.getIsSelected?.() || false;
const canSelectCell =
(selection === "single-cell" || selection === "multi-cell") &&
diff --git a/frontend/src/components/data-table/date-popover.tsx b/frontend/src/components/data-table/date-popover.tsx
index 5705280aad..67a8e558e5 100644
--- a/frontend/src/components/data-table/date-popover.tsx
+++ b/frontend/src/components/data-table/date-popover.tsx
@@ -1,5 +1,5 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import React from "react";
+import React, { useMemo } from "react";
import { useDateFormatter, useLocale } from "react-aria";
import { Tooltip } from "@/components/ui/tooltip";
@@ -45,6 +45,7 @@ export const DatePopover: React.FC<DatePopoverProps> = ({
const TimezoneDisplay = ({ date }: { date: Date }) => {
const { locale } = useLocale();
+ // The system timezone can change without the locale changing.
const localTimezone = new Intl.DateTimeFormat(locale).resolvedOptions()
.timeZone;
const hasSubSeconds = date.getUTCMilliseconds() !== 0;
@@ -116,9 +117,10 @@ const RelativeTime = ({ date }: { date: Date }) => {
const { locale } = useLocale();
// Initialize relative time formatter with current locale and "auto" numeric style
- const relativeTimeFormatter = new Intl.RelativeTimeFormat(locale, {
- numeric: "auto",
- });
+ const relativeTimeFormatter = useMemo(
+ () => new Intl.RelativeTimeFormat(locale, { numeric: "auto" }),
+ [locale],
+ );
const currentTime = new Date();
// Get difference in seconds between now and the input date
diff --git a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
index f9f3864d33..7eb75a4163 100644
--- a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
+++ b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
@@ -34,6 +34,7 @@ import { DelayMount } from "@/components/utils/delay-mount";
import { useAsyncData } from "@/hooks/useAsyncData";
import { Banner, ErrorBanner } from "@/plugins/impl/common/error-banner";
import type { GetRowResult } from "@/plugins/impl/DataTablePlugin";
+import { Objects } from "@/utils/objects";
import { NAMELESS_COLUMN_PREFIX, renderCellValue } from "../columns";
import { prettifyRowCount } from "../pagination";
import {
@@ -88,8 +89,7 @@ export const RowViewerPanel: React.FC<RowViewerPanelProps> = ({
handleRowSelectionChange?.((prev) => {
if (isRowSelected) {
// Remove this row from selection
- const { [rowIdx]: removedRow, ...rest } = prev;
- return rest;
+ return Objects.filter(prev, (_, key) => key !== String(rowIdx));
}
// Add this row to selection
return { ...prev, [rowIdx]: true };
diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
index ecb7dde208..16a18ce65a 100644
--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx
+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
@@ -106,9 +106,9 @@ export const AddCellWithAI: React.FC<{
const runtimeManager = useRuntimeManager();
const inputRef = useRef<ReactCodeMirrorRef>(null);
- const submissionController = useRef(
- new StagedCellSubmissionController(),
- ).current;
+ const [submissionController] = useState(
+ () => new StagedCellSubmissionController(),
+ );
const fileInputRef = useRef<HTMLInputElement>(null);
const { files, addFiles, removeFile } = useFileState();
diff --git a/frontend/src/components/editor/connections/components.tsx b/frontend/src/components/editor/connections/components.tsx
index fe5e9ac28e..fee24f7fb0 100644
--- a/frontend/src/components/editor/connections/components.tsx
+++ b/frontend/src/components/editor/connections/components.tsx
@@ -48,7 +48,7 @@ export const SelectorButton: React.FC<{
}> = ({ name, color, icon, onSelect }) => (
<button
type="button"
- className="py-3 flex flex-col items-center justify-center gap-1 transition-all hover:scale-105 hover:brightness-110 rounded shadow-sm-solid hover:shadow-md-solid"
+ className="py-3 flex flex-col items-center justify-center gap-1 transition-[scale,filter,box-shadow] hover:scale-105 hover:brightness-110 rounded shadow-sm-solid hover:shadow-md-solid"
style={{ backgroundColor: color }}
onClick={onSelect}
>
diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
index 8df7e60bee..a97a6cb7f8 100644
--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
@@ -248,7 +248,7 @@ export const replaceTracebackFilenames = (domNode: DOMNode) => {
<Tooltip content={tooltipContent}>
<button
type="button"
- className="ml-1 p-1 rounded-sm hover:bg-muted transition-all inline"
+ className="ml-1 p-1 rounded-sm hover:bg-muted transition-colors inline"
>
<BugPlayIcon
onClick={() => {
diff --git a/frontend/src/components/pages/home-page.tsx b/frontend/src/components/pages/home-page.tsx
index aba169f0a3..a024471425 100644
--- a/frontend/src/components/pages/home-page.tsx
+++ b/frontend/src/components/pages/home-page.tsx
@@ -514,7 +514,7 @@ const MarimoFileComponent = ({ file }: { file: MarimoFile }) => {
return (
<a
- className="py-1.5 px-4 hover:bg-(--blue-2) hover:text-primary transition-all duration-300 cursor-pointer group relative flex gap-4 items-center"
+ className="py-1.5 px-4 hover:bg-(--blue-2) hover:text-primary transition-colors duration-300 cursor-pointer group relative flex gap-4 items-center"
key={file.path}
href={href.toString()}
target={tabTarget(file.initializationId || file.path)}
@@ -542,7 +542,7 @@ const MarimoFileComponent = ({ file }: { file: MarimoFile }) => {
</div>
<ExternalLinkIcon
size={20}
- className="group-hover:opacity-100 opacity-0 transition-all duration-300 text-primary"
+ className="group-hover:opacity-100 opacity-0 transition-opacity duration-300 text-primary"
/>
</div>
{!!file.lastModified && (
@@ -617,14 +617,14 @@ const CreateNewNotebook: React.FC = () => {
<a
className="relative rounded-lg p-6 group
text-primary hover:bg-(--blue-2) shadow-md-solid shadow-accent border bg-(--blue-1)
- transition-all duration-300 cursor-pointer
+ transition-colors duration-300 cursor-pointer
"
href={url}
target="_blank"
rel="noreferrer"
>
<h2 className="text-lg font-semibold">Create a new notebook</h2>
- <div className="group-hover:opacity-100 opacity-0 absolute right-5 top-0 bottom-0 rounded-lg flex items-center justify-center transition-all duration-300">
+ <div className="group-hover:opacity-100 opacity-0 absolute right-5 top-0 bottom-0 rounded-lg flex items-center justify-center transition-opacity duration-300">
<ExternalLinkIcon size={24} />
</div>
</a>
diff --git a/frontend/src/components/tracing/tracing.tsx b/frontend/src/components/tracing/tracing.tsx
index 6acd100a2e..bb0fddce4b 100644
--- a/frontend/src/components/tracing/tracing.tsx
+++ b/frontend/src/components/tracing/tracing.tsx
@@ -145,11 +145,11 @@ const TraceBlock: React.FC<{
isMostRecentRun: boolean;
chartPosition: ChartPosition;
theme: ResolvedTheme;
-}> = ({ run, isMostRecentRun, chartPosition, isExpanded, theme }) => {
+}> = ({ run, isMostRecentRun, chartPosition, isExpanded: expanded, theme }) => {
const setExpandedRuns = useSetAtom(expandedRunsAtom);
// We prefer the user's last click, but if they haven't clicked on this run,
// we expand the most recent run by default, otherwise we collapse it.
- isExpanded = isExpanded ?? isMostRecentRun;
+ const isExpanded = expanded ?? isMostRecentRun;
const onToggleExpanded = () => {
setExpandedRuns((prev) => {
diff --git a/frontend/src/core/cells/pending-delete-service.ts b/frontend/src/core/cells/pending-delete-service.ts
index 9984d3e2ea..cd38ce087e 100644
--- a/frontend/src/core/cells/pending-delete-service.ts
+++ b/frontend/src/core/cells/pending-delete-service.ts
@@ -134,12 +134,8 @@ export function usePendingDeleteService() {
submit({ cellIds, deleteCell, deleteManyCells, store });
},
clear,
- get idle() {
- return entries.size === 0;
- },
- get shouldConfirmDelete() {
- return entries.size > 1;
- },
+ idle: entries.size === 0,
+ shouldConfirmDelete: entries.size > 1,
};
}
diff --git a/frontend/src/core/datasets/__tests__/data-source-discovery.test.ts b/frontend/src/core/datasets/__tests__/data-source-discovery.test.ts
index 784118d525..fa9c0268e7 100644
--- a/frontend/src/core/datasets/__tests__/data-source-discovery.test.ts
+++ b/frontend/src/core/datasets/__tests__/data-source-discovery.test.ts
@@ -185,8 +185,8 @@ describe("isDetectedSourceConnected", () => {
});
const emptySnapshot = {
dialects: [] as string[],
- storageProtocols: [] as string[],
- storageBackendTypes: [] as string[],
+ storageProtocols: new Set<string>(),
+ storageBackendTypes: new Set<string>(),
};
it("does not hide a source when nothing is connected", () => {
@@ -242,7 +242,7 @@ describe("isDetectedSourceConnected", () => {
expect(
isDetectedSourceConnected(s3, {
...emptySnapshot,
- storageProtocols: ["s3"],
+ storageProtocols: new Set(["s3"]),
}),
).toBe(true);
});
@@ -262,7 +262,7 @@ describe("isDetectedSourceConnected", () => {
expect(
isDetectedSourceConnected(hf, {
...emptySnapshot,
- storageBackendTypes: ["huggingface"],
+ storageBackendTypes: new Set(["huggingface"]),
}),
).toBe(true);
});
diff --git a/frontend/src/core/datasets/data-source-discovery.ts b/frontend/src/core/datasets/data-source-discovery.ts
index f4588fe1bd..b85c70aafc 100644
--- a/frontend/src/core/datasets/data-source-discovery.ts
+++ b/frontend/src/core/datasets/data-source-discovery.ts
@@ -27,8 +27,8 @@ export function matchesDiscoveryGroup(
*/
export interface LiveConnectionSnapshot {
dialects: readonly string[];
- storageProtocols: readonly string[];
- storageBackendTypes: readonly string[];
+ storageProtocols: ReadonlySet<string>;
+ storageBackendTypes: ReadonlySet<string>;
}
/**
@@ -47,15 +47,13 @@ export function isDetectedSourceConnected(
}
if (
- match.protocols.some((protocol) =>
- snapshot.storageProtocols.includes(protocol),
- )
+ match.protocols.some((protocol) => snapshot.storageProtocols.has(protocol))
) {
return true;
}
return match.backendTypes.some((backendType) =>
- snapshot.storageBackendTypes.includes(backendType),
+ snapshot.storageBackendTypes.has(backendType),
);
}
diff --git a/frontend/src/core/hotkeys/actions.ts b/frontend/src/core/hotkeys/actions.ts
index 58f469e1cf..1464a9f7e7 100644
--- a/frontend/src/core/hotkeys/actions.ts
+++ b/frontend/src/core/hotkeys/actions.ts
@@ -2,6 +2,7 @@
import { atom, useAtomValue, useSetAtom } from "jotai";
import useEvent from "react-use-event-hook";
import type { HotkeyAction } from "@/core/hotkeys/hotkeys";
+import { Objects } from "@/utils/objects";
/**
* Map of registered keyboard shortcuts and their callbacks.
@@ -29,10 +30,7 @@ export function useSetRegisteredAction() {
},
),
unregisterAction: useEvent((shortcut: HotkeyAction) => {
- set((actions) => {
- const { [shortcut]: unused, ...rest } = actions;
- return rest;
- });
+ set((actions) => Objects.omit(actions, [shortcut]));
}),
};
}
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index 12d24db6f6..05713eb86b 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -10,6 +10,8 @@ import { isStaticNotebook } from "../static/static-state";
import { isWasm } from "../wasm/utils";
import type { RuntimeConfig } from "./types";
+const knownQueryParams = new Set(Object.values(KnownQueryParams));
+
export class RuntimeManager {
private initialHealthyCheck = new Deferred<void>();
private config: RuntimeConfig;
@@ -72,10 +74,7 @@ export class RuntimeManager {
}
for (const [key, value] of currentParams.entries()) {
- if (
- restrictToKnownQueryParams &&
- !Object.values(KnownQueryParams).includes(key)
- ) {
+ if (restrictToKnownQueryParams && !knownQueryParams.has(key)) {
continue;
}
baseUrl.searchParams.set(key, value);
diff --git a/frontend/src/hooks/__tests__/useAsyncData.test.tsx b/frontend/src/hooks/__tests__/useAsyncData.test.tsx
new file mode 100644
index 0000000000..e92101938a
--- /dev/null
+++ b/frontend/src/hooks/__tests__/useAsyncData.test.tsx
@@ -0,0 +1,148 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { act, render, renderHook, waitFor } from "@testing-library/react";
+import { Activity } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { Deferred } from "@/utils/Deferred";
+import { useAsyncData } from "../useAsyncData";
+
+function AsyncDataStatus({ fetch }: { fetch: () => Promise<string> }) {
+ const result = useAsyncData(fetch, []);
+ return (
+ <output
+ data-status={result.status}
+ data-fetching={result.isFetching}
+ data-error={result.error?.message ?? ""}
+ >
+ {result.data}
+ </output>
+ );
+}
+
+describe("useAsyncData", () => {
+ it.each(["success", "error"] as const)(
+ "restarts fetching when Activity reopens after %s",
+ async (initialStatus) => {
+ const initial = new Deferred<string>();
+ const restarted = new Deferred<string>();
+ const fetch = vi
+ .fn(() => restarted.promise)
+ .mockImplementationOnce(() => initial.promise);
+ const view = render(
+ <Activity mode="visible">
+ <AsyncDataStatus fetch={fetch} />
+ </Activity>,
+ );
+ await act(async () => {
+ if (initialStatus === "success") {
+ initial.resolve("first");
+ } else {
+ initial.reject(new Error("offline"));
+ }
+ });
+ expect(view.getByRole("status").dataset.status).toBe(initialStatus);
+
+ view.rerender(
+ <Activity mode="hidden">
+ <AsyncDataStatus fetch={fetch} />
+ </Activity>,
+ );
+ view.rerender(
+ <Activity mode="visible">
+ <AsyncDataStatus fetch={fetch} />
+ </Activity>,
+ );
+
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(view.getByRole("status").dataset).toMatchObject({
+ status: initialStatus === "success" ? "loading" : "pending",
+ error: "",
+ fetching: "true",
+ });
+ expect(view.getByRole("status").textContent).toBe(
+ initialStatus === "success" ? "first" : "",
+ );
+ await act(async () => restarted.resolve("latest"));
+ expect(view.getByRole("status").dataset).toMatchObject({
+ status: "success",
+ fetching: "false",
+ });
+ expect(view.getByRole("status").textContent).toBe("latest");
+ },
+ );
+
+ it("ignores a request canceled when Activity hides", async () => {
+ const canceled = new Deferred<string>();
+ const restarted = new Deferred<string>();
+ const fetch = vi
+ .fn(() => restarted.promise)
+ .mockImplementationOnce(() => canceled.promise);
+ const view = render(
+ <Activity mode="visible">
+ <AsyncDataStatus fetch={fetch} />
+ </Activity>,
+ );
+ view.rerender(
+ <Activity mode="hidden">
+ <AsyncDataStatus fetch={fetch} />
+ </Activity>,
+ );
+ view.rerender(
+ <Activity mode="visible">
+ <AsyncDataStatus fetch={fetch} />
+ </Activity>,
+ );
+ expect(fetch).toHaveBeenCalledTimes(2);
+ await act(async () => canceled.resolve("obsolete"));
+ expect(view.getByRole("status").dataset.status).toBe("pending");
+ expect(view.getByRole("status").textContent).toBe("");
+ await act(async () => restarted.resolve("latest"));
+ expect(view.getByRole("status").dataset.status).toBe("success");
+ expect(view.getByRole("status").textContent).toBe("latest");
+ });
+
+ it("preserves data while refetching and ignores obsolete requests", async () => {
+ const requests = [
+ new Deferred<string>(),
+ new Deferred<string>(),
+ new Deferred<string>(),
+ ];
+ const fetch = vi
+ .fn(() => requests[0].promise)
+ .mockImplementationOnce(() => requests[0].promise)
+ .mockImplementationOnce(() => requests[1].promise)
+ .mockImplementationOnce(() => requests[2].promise);
+ const { result, rerender } = renderHook(
+ ({ key }) => useAsyncData(fetch, [key]),
+ { initialProps: { key: 0 } },
+ );
+ expect(result.current.status).toBe("pending");
+ await act(async () => requests[0].resolve("first"));
+ expect(result.current.data).toBe("first");
+ rerender({ key: 1 });
+ expect(result.current).toMatchObject({ status: "loading", data: "first" });
+ rerender({ key: 2 });
+ await act(async () => requests[1].resolve("obsolete"));
+ expect(result.current).toMatchObject({ status: "loading", data: "first" });
+ await act(async () => requests[2].resolve("latest"));
+ expect(result.current).toMatchObject({ status: "success", data: "latest" });
+ });
+
+ it("retries after errors and allows manual updates during a request", async () => {
+ const request = new Deferred<string>();
+ const fetch = vi
+ .fn<() => Promise<string>>()
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockImplementation(() => request.promise);
+ const { result } = renderHook(() => useAsyncData(fetch, []));
+ await waitFor(() => expect(result.current.status).toBe("error"));
+ act(() => result.current.refetch());
+ expect(result.current.status).toBe("pending");
+ act(() => result.current.setData("manual"));
+ expect(result.current).toMatchObject({ status: "success", data: "manual" });
+ await act(async () => request.resolve("response"));
+ expect(result.current).toMatchObject({
+ status: "success",
+ data: "response",
+ });
+ });
+});
diff --git a/frontend/src/hooks/useAsyncData.ts b/frontend/src/hooks/useAsyncData.ts
index 9c45c72f0b..f3e4e6ef29 100644
--- a/frontend/src/hooks/useAsyncData.ts
+++ b/frontend/src/hooks/useAsyncData.ts
@@ -322,7 +322,7 @@ export function useAsyncData<T>(
const [nonce, setNonce] = useState(0);
const [result, setResult] = useState<
PendingResult<T> | LoadingResult<T> | ErrorResult<T> | SuccessResult<T>
- >(Result.pending());
+ >(() => Result.pending());
const asProps =
typeof loaderOrProps === "function"
@@ -339,12 +339,12 @@ export function useAsyncData<T>(
keepPrevious = true;
},
};
+ // Activity can restart this effect without changing dependencies, so
+ // loading state must follow the request lifecycle.
setResult((prevResult) => {
- // If we have previous data, show reloading state
if (prevResult.status === "success" || prevResult.status === "loading") {
return Result.loading(prevResult.data);
}
- // Otherwise, show initial loading state
return Result.pending();
});
fetchStable(context)
diff --git a/frontend/src/hooks/useDataSourceDiscovery.ts b/frontend/src/hooks/useDataSourceDiscovery.ts
index 48b650e91c..514d26ad59 100644
--- a/frontend/src/hooks/useDataSourceDiscovery.ts
+++ b/frontend/src/hooks/useDataSourceDiscovery.ts
@@ -42,11 +42,13 @@ export function useDetectedDataSources(
dialects: [...connections.values()].map((connection) =>
connection.dialect.toLowerCase(),
),
- storageProtocols: storageNamespaces.map((namespace) =>
- namespace.protocol.toLowerCase(),
+ storageProtocols: new Set(
+ storageNamespaces.map((namespace) => namespace.protocol.toLowerCase()),
),
- storageBackendTypes: storageNamespaces.map((namespace) =>
- namespace.backendType.toLowerCase(),
+ storageBackendTypes: new Set(
+ storageNamespaces.map((namespace) =>
+ namespace.backendType.toLowerCase(),
+ ),
),
};
diff --git a/frontend/src/hooks/useElapsedTime.ts b/frontend/src/hooks/useElapsedTime.ts
index ccad23fc5c..09d6e1c4a0 100644
--- a/frontend/src/hooks/useElapsedTime.ts
+++ b/frontend/src/hooks/useElapsedTime.ts
@@ -1,13 +1,13 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import { type Milliseconds, Time } from "@/utils/time";
/**
* Returns the elapsed time since mount, in milliseconds.
*/
export function useElapsedTime(initialStartTimeMs: Milliseconds) {
- const startTime = useRef(initialStartTimeMs);
+ const [startTime] = useState(initialStartTimeMs);
const [endTime, setEndTime] = useState(initialStartTimeMs);
useEffect(() => {
@@ -21,5 +21,5 @@ export function useElapsedTime(initialStartTimeMs: Milliseconds) {
return () => clearInterval(interval);
}, []);
- return endTime - startTime.current;
+ return endTime - startTime;
}
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index 233631b134..657b52b527 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -104,7 +104,7 @@ function PluginSlotInternal<T>(
ref: React.Ref<PluginSlotHandle>,
): JSX.Element {
const [childNodes, setChildNodes] = useState<ReactNode>(children);
- const [value, setValue] = useState<T>(getInitialValue());
+ const [value, setValue] = useState<T>(getInitialValue);
const { theme } = useTheme();
const [parsedResult, setParsedResult] = useState(() => {
diff --git a/frontend/src/plugins/impl/DropdownPlugin.tsx b/frontend/src/plugins/impl/DropdownPlugin.tsx
index 7b61037f20..31ca48e07e 100644
--- a/frontend/src/plugins/impl/DropdownPlugin.tsx
+++ b/frontend/src/plugins/impl/DropdownPlugin.tsx
@@ -97,13 +97,9 @@ const Dropdown = (props: DropdownProps): JSX.Element => {
id={id}
disabled={disabled}
>
- {allowSelectNone ? (
- <option value={EMPTY_VALUE} selected={value.length === 0}>
- --
- </option>
- ) : null}
+ {allowSelectNone ? <option value={EMPTY_VALUE}>--</option> : null}
{options.map((option) => (
- <option value={option} selected={value.includes(option)} key={option}>
+ <option value={option} key={option}>
{option}
</option>
))}
diff --git a/frontend/src/plugins/impl/FormPlugin.tsx b/frontend/src/plugins/impl/FormPlugin.tsx
index b5ded59b47..06f210f4b7 100644
--- a/frontend/src/plugins/impl/FormPlugin.tsx
+++ b/frontend/src/plugins/impl/FormPlugin.tsx
@@ -212,7 +212,7 @@ const Form = ({
// wrapped plugin; this buffered value is in contrast to the actual
// value of the plugin, which is the value of the wrapped plugin when
// the submit button was last clicked/activated.
- const [internalValue, setInternalValue] = useState<T>(
+ const [internalValue, setInternalValue] = useState<T>(() =>
UI_ELEMENT_REGISTRY.lookupValue(elementId),
);
diff --git a/frontend/src/plugins/impl/code/any-language-editor.tsx b/frontend/src/plugins/impl/code/any-language-editor.tsx
index fffd4628aa..ffbe34b70b 100644
--- a/frontend/src/plugins/impl/code/any-language-editor.tsx
+++ b/frontend/src/plugins/impl/code/any-language-editor.tsx
@@ -53,14 +53,14 @@ const AnyLanguageCodeMirror: React.FC<
extensions?: readonly Extension[];
}
> = ({
- language,
+ language: requestedLanguage,
hideUnsupportedLanguageErrors,
showCopyButton,
extensions = EMPTY_EXTENSIONS,
...props
}) => {
// Maybe normalize the language to the extension
- language = LANGUAGE_MAP[language || ""] || language;
+ const language = LANGUAGE_MAP[requestedLanguage || ""] || requestedLanguage;
const isSupported = isSupportedLanguage(language);
if (!isSupported) {
diff --git a/frontend/src/plugins/impl/data-editor/glide-data-editor.tsx b/frontend/src/plugins/impl/data-editor/glide-data-editor.tsx
index f187d2cb2e..a320d7f92b 100644
--- a/frontend/src/plugins/impl/data-editor/glide-data-editor.tsx
+++ b/frontend/src/plugins/impl/data-editor/glide-data-editor.tsx
@@ -73,12 +73,16 @@ export const GlideDataEditor = ({
});
const [columnWidths, setColumnWidths] = useState<Record<string, number>>({});
+ const editableColumnSet = useMemo(
+ () => (editableColumns === "all" ? null : new Set(editableColumns)),
+ [editableColumns],
+ );
const columns: ModifiedGridColumn[] = useMemo(() => {
const columns: ModifiedGridColumn[] = [];
for (const [columnName, fieldType] of columnFields) {
const editable =
- editableColumns === "all" || editableColumns.includes(columnName);
+ editableColumnSet === null || editableColumnSet.has(columnName);
columns.push({
id: columnName,
@@ -100,7 +104,7 @@ export const GlideDataEditor = ({
}
return columns;
- }, [columnFields, columnWidths, editableColumns, theme]);
+ }, [columnFields, columnWidths, editableColumnSet, theme]);
const getCellContent = useCallback(
(cell: Item): GridCell => {
@@ -110,8 +114,7 @@ export const GlideDataEditor = ({
const dataItem = dataRow[columns[col].title];
const columnKind = columns[col].kind;
const editable =
- editableColumns === "all" ||
- editableColumns.includes(columns[col].title);
+ editableColumnSet === null || editableColumnSet.has(columns[col].title);
if (columnKind === GridCellKind.Boolean) {
const value = Boolean(dataItem);
@@ -141,7 +144,7 @@ export const GlideDataEditor = ({
data: String(dataItem),
};
},
- [columns, data, editableColumns],
+ [columns, data, editableColumnSet],
);
const onCellEdited = useCallback(
diff --git a/frontend/src/plugins/impl/data-editor/glide-utils.ts b/frontend/src/plugins/impl/data-editor/glide-utils.ts
index 187cf57148..71fa881a2a 100644
--- a/frontend/src/plugins/impl/data-editor/glide-utils.ts
+++ b/frontend/src/plugins/impl/data-editor/glide-utils.ts
@@ -147,6 +147,8 @@ export function pasteCells(options: {
}
const edits: Edits["edits"] = [];
+ const editableColumnSet =
+ editableColumns === "all" ? null : new Set(editableColumns);
for (const [rowIndex, dataRow] of parsedData.entries()) {
if (!dataRow) {
@@ -175,7 +177,7 @@ export function pasteCells(options: {
const column = columns[targetColIdx];
const columnType = column.dataType;
const editable =
- editableColumns === "all" || editableColumns.includes(column.title);
+ editableColumnSet === null || editableColumnSet.has(column.title);
if (!editable) {
continue;
diff --git a/frontend/src/plugins/impl/vega/make-selectable.ts b/frontend/src/plugins/impl/vega/make-selectable.ts
index 89ab4bcf1d..8631bac47b 100644
--- a/frontend/src/plugins/impl/vega/make-selectable.ts
+++ b/frontend/src/plugins/impl/vega/make-selectable.ts
@@ -3,6 +3,7 @@
import type { TopLevelSpec } from "vega-lite";
import type { NonNormalizedSpec } from "vega-lite/types_unstable/spec/index.js";
import type { TopLevelParameter } from "vega-lite/types_unstable/spec/toplevel.js";
+import { Arrays } from "@/utils/arrays";
import { findEncodedFields, makeEncodingInteractive } from "./encodings";
import { Marks } from "./marks";
@@ -357,9 +358,7 @@ export function makeSelectable<T extends VegaLiteSpec>(
// If fieldSelection is an array, filter the fields
if (Array.isArray(fieldSelection)) {
- legendFields = legendFields.filter((field) =>
- fieldSelection.includes(field),
- );
+ legendFields = Arrays.intersection(legendFields, fieldSelection);
}
}
@@ -420,9 +419,7 @@ function makeLegendSelectable(
let legendFields = findEncodedFields(spec);
// If fieldSelection is an array, we filter the fields
if (Array.isArray(fieldSelection)) {
- legendFields = legendFields.filter((field) =>
- fieldSelection.includes(field),
- );
+ legendFields = Arrays.intersection(legendFields, fieldSelection);
}
const legendParams = legendFields.map((field) => Params.legend(field));
diff --git a/frontend/src/utils/__tests__/arrays.test.ts b/frontend/src/utils/__tests__/arrays.test.ts
index d0da77e195..7b0464c45b 100644
--- a/frontend/src/utils/__tests__/arrays.test.ts
+++ b/frontend/src/utils/__tests__/arrays.test.ts
@@ -16,6 +16,41 @@ import {
} from "../arrays";
describe("arrays", () => {
+ describe.each([
+ ["intersection", Arrays.intersection, [3, 3, 2], [Number.NaN]],
+ ["difference", Arrays.difference, [1], [1]],
+ ] as const)("%s", (_name, operation, expected, expectedWithNaN) => {
+ it("preserves order and duplicates without mutating readonly inputs", () => {
+ const values = Object.freeze([3, 1, 3, 2]);
+ const other = Object.freeze([2, 3, 3]);
+ expect(operation(values, other)).toEqual(expected);
+ expect(values).toEqual([3, 1, 3, 2]);
+ expect(other).toEqual([2, 3, 3]);
+ });
+
+ it("uses the same equality as array membership, including NaN", () => {
+ expect(operation([Number.NaN, 1], [Number.NaN])).toEqual(expectedWithNaN);
+ });
+
+ it("handles an empty source", () => {
+ expect(operation([], [1])).toEqual([]);
+ });
+ });
+
+ it("handles empty membership lists", () => {
+ expect(Arrays.intersection([1, 1, 2], [])).toEqual([]);
+ expect(Arrays.difference([1, 1, 2], [])).toEqual([1, 1, 2]);
+ });
+
+ it("compares objects by identity", () => {
+ const shared = { id: 1 };
+ const distinct = { id: 1 };
+ expect(Arrays.intersection([shared, distinct], [shared])).toEqual([shared]);
+ expect(Arrays.difference([shared, distinct], [shared])).toEqual([distinct]);
+ expect(Arrays.intersection([shared, distinct], [shared])[0]).toBe(shared);
+ expect(Arrays.difference([shared, distinct], [shared])[0]).toBe(distinct);
+ });
+
describe("arrayDelete", () => {
it("should delete an element at the specified index", () => {
expect(arrayDelete([1, 2, 3], 1)).toEqual([1, 3]);
diff --git a/frontend/src/utils/__tests__/numbers.test.ts b/frontend/src/utils/__tests__/numbers.test.ts
index 36d71e3877..f8edea3167 100644
--- a/frontend/src/utils/__tests__/numbers.test.ts
+++ b/frontend/src/utils/__tests__/numbers.test.ts
@@ -1,5 +1,5 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import {
countFractionDigits,
maxFractionDigitsForSteps,
@@ -20,6 +20,53 @@ describe("prettyNumber", () => {
const options = { locale };
+describe("formatter reuse", () => {
+ it.each([
+ {
+ name: "scientific",
+ value: 0.000_123_4,
+ format: (value: number, locale: string) =>
+ prettyScientificNumber(value, { locale }),
+ },
+ {
+ name: "rounded",
+ value: 1234.567,
+ format: (value: number, locale: string) =>
+ prettyScientificNumber(value, { locale, shouldRound: true }),
+ },
+ {
+ name: "engineering",
+ value: 12_345,
+ format: prettyEngineeringNumber,
+ },
+ ])(
+ "reuses the $name formatter until the locale changes",
+ ({ format, value }) => {
+ const NumberFormat = Intl.NumberFormat;
+ const constructor = vi
+ .spyOn(Intl, "NumberFormat")
+ .mockImplementation(function (locales, options) {
+ return new NumberFormat(locales, options);
+ });
+ try {
+ const first = format(value, "fr-FR");
+ expect(format(value, "fr-FR")).toBe(first);
+ format(value * 2, "fr-FR");
+ expect(constructor).toHaveBeenCalledTimes(1);
+
+ format(value, "de-DE");
+ expect(constructor).toHaveBeenCalledTimes(2);
+ expect(constructor).toHaveBeenLastCalledWith(
+ "de-DE",
+ expect.any(Object),
+ );
+ } finally {
+ constructor.mockRestore();
+ }
+ },
+ );
+});
+
describe("prettyScientificNumber", () => {
it("should handle special cases", () => {
expect(prettyScientificNumber(0, options)).toBe("0");
diff --git a/frontend/src/utils/__tests__/objects.test.ts b/frontend/src/utils/__tests__/objects.test.ts
index a8ffc72244..4b4d480413 100644
--- a/frontend/src/utils/__tests__/objects.test.ts
+++ b/frontend/src/utils/__tests__/objects.test.ts
@@ -204,6 +204,27 @@ describe("Objects", () => {
});
describe("filter", () => {
+ it.each([42, { base_url: "https://example.com" }])(
+ "preserves an own __proto__ property with value %j",
+ (value) => {
+ const obj = { ["__proto__"]: value, removed: value };
+ const result = Objects.filter(obj, (_, key) => key !== "removed");
+
+ expect(Object.entries(result)).toEqual([["__proto__", value]]);
+ expect(Object.getPrototypeOf(result)).toBe(Object.prototype);
+ expect(Object.getOwnPropertyDescriptor(result, "__proto__")).toEqual({
+ value,
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ });
+ expect(Object.keys(obj)).toEqual(["__proto__", "removed"]);
+ expect(Objects.filter(obj, (_, key) => key !== "__proto__")).toEqual({
+ removed: value,
+ });
+ },
+ );
+
it("should filter object entries by predicate", () => {
const obj = { a: 1, b: 2, c: 3, d: 4 };
const result = Objects.filter(obj, (v) => v % 2 === 0);
diff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.ts
index a14c1bff2d..a6c7e0709d 100644
--- a/frontend/src/utils/arrays.ts
+++ b/frontend/src/utils/arrays.ts
@@ -55,6 +55,16 @@ export function arrayShallowEquals<T>(a: T[], b: T[]): boolean {
export const Arrays = {
// oxlint-disable-next-line typescript/no-explicit-any
EMPTY: [] as any,
+ /** Keep values present in both arrays, preserving the first array's order and duplicates. */
+ intersection<T>(values: readonly T[], included: readonly T[]): T[] {
+ const includedSet = new Set(included);
+ return values.filter((value) => includedSet.has(value));
+ },
+ /** Remove values present in the second array, preserving order and duplicates. */
+ difference<T>(values: readonly T[], excluded: readonly T[]): T[] {
+ const excludedSet = new Set(excluded);
+ return values.filter((value) => !excludedSet.has(value));
+ },
zip: <T, U>(a: T[], b: U[]): [T, U][] => {
invariant(a.length === b.length, "Arrays must be the same length");
return a.map((item, i) => [item, b[i]]);
diff --git a/frontend/src/utils/numbers.ts b/frontend/src/utils/numbers.ts
index a9283eea59..200bdf7791 100644
--- a/frontend/src/utils/numbers.ts
+++ b/frontend/src/utils/numbers.ts
@@ -23,6 +23,31 @@ export const maxFractionalDigits = memoizeLastValue((locale: string) => {
return 0;
});
+const getScientificFormatter = memoizeLastValue(
+ (locale: string) =>
+ new Intl.NumberFormat(locale, {
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1,
+ notation: "scientific",
+ }),
+);
+
+const getRoundedFormatter = memoizeLastValue(
+ (locale: string) =>
+ new Intl.NumberFormat(locale, {
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 2,
+ }),
+);
+
+const getEngineeringFormatter = memoizeLastValue(
+ (locale: string) =>
+ new Intl.NumberFormat(locale, {
+ notation: "engineering",
+ maximumSignificantDigits: 3,
+ }),
+);
+
/** Decimal places needed to display `n` without float noise. */
export function countFractionDigits(n: number): number {
if (!Number.isFinite(n) || n === 0) {
@@ -108,23 +133,14 @@ export function prettyScientificNumber(
// Determine if the number should be in scientific notation
const absValue = Math.abs(value);
if (absValue < 1e-2 || absValue >= 1e6) {
- return new Intl.NumberFormat(opts.locale, {
- minimumFractionDigits: 1,
- maximumFractionDigits: 1,
- notation: "scientific",
- })
- .format(value)
- .toLowerCase();
+ return getScientificFormatter(opts.locale).format(value).toLowerCase();
}
const { shouldRound, locale } = opts;
if (shouldRound) {
// Number has an integer part, format with 2 decimal places
- return new Intl.NumberFormat(locale, {
- minimumFractionDigits: 0,
- maximumFractionDigits: 2,
- }).format(value);
+ return getRoundedFormatter(locale).format(value);
}
// Don't round
@@ -161,12 +177,7 @@ export function prettyEngineeringNumber(value: number, locale: string): string {
return specialCase;
}
- const [mant, exp] = new Intl.NumberFormat(locale, {
- notation: "engineering",
- maximumSignificantDigits: 3,
- })
- .format(value)
- .split("E");
+ const [mant, exp] = getEngineeringFormatter(locale).format(value).split("E");
if (exp in prefixes) {
return mant + prefixes[exp as keyof typeof prefixes];
diff --git a/frontend/src/utils/objects.ts b/frontend/src/utils/objects.ts
index 0963b1f166..e128038c5a 100644
--- a/frontend/src/utils/objects.ts
+++ b/frontend/src/utils/objects.ts
@@ -89,13 +89,9 @@ export const Objects = {
obj: Record<K, V>,
predicate: (value: V, key: K) => boolean,
): Record<K, V> {
- const result: Record<K, V> = {} as Record<K, V>;
- for (const [key, value] of Objects.entries(obj)) {
- if (predicate(value, key)) {
- result[key] = obj[key];
- }
- }
- return result;
+ return Objects.fromEntries(
+ Objects.entries(obj).filter(([key, value]) => predicate(value, key)),
+ );
},
omit<V extends object, K extends keyof V>(