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.

improvement: reduce react compiler lint errors for better react compiler coverage (#3043)

Myles Scolnicke07943d9cc14
diff --git a/frontend/package.json b/frontend/package.json
index 56f68c906b..c82a9bf638 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -26,9 +26,9 @@
"@codemirror/theme-one-dark": "^6.1.2",
"@codemirror/view": "^6.34.1",
"@dagrejs/dagre": "^1.1.4",
- "@dnd-kit/core": "^6.1.0",
- "@dnd-kit/modifiers": "^7.0.0",
- "@dnd-kit/sortable": "^8.0.0",
+ "@dnd-kit/core": "^6.2.0",
+ "@dnd-kit/modifiers": "^8.0.0",
+ "@dnd-kit/sortable": "^9.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@emotion/cache": "^11.13.1",
"@emotion/react": "^11.13.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index db91638e8a..385352284f 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -55,14 +55,14 @@ importers:
specifier: ^1.1.4
version: 1.1.4
'@dnd-kit/core':
- specifier: ^6.1.0
+ specifier: ^6.2.0
'@dnd-kit/modifiers':
- specifier: ^7.0.0
- '@dnd-kit/sortable':
specifier: ^8.0.0
+ '@dnd-kit/sortable':
+ specifier: ^9.0.0
'@dnd-kit/utilities':
specifier: ^3.2.2
version: 3.2.2([email protected])
@@ -1078,27 +1078,27 @@ packages:
resolution: {integrity: sha512-mepCf/e9+SKYy1d02/UkvSy6+6MoyXhVxP8lLDfA7BPE1X1d4dR0sZznmbM8/XVJ1GPM+Svnx7Xj6ZweByWUkw==}
engines: {node: '>17.0.0'}
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-ea7IkhKvlJUv9iSHJOnxinBcoOI3ppGnnL+VDJ75O45Nss6HtZd8IdN8touXPDtASfeI2T2LImb8VOZcL47wjQ==}
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}
peerDependencies:
react: '>=16.8.0'
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-J3cQBClB4TVxwGo3KEjssGEXNJqGVWx17aRTZ1ob0FliR5IjYgTxl5YJbKTzA6IzrtelotH19v6y7uoIRUZPSg==}
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-KVK/CJmaYGTxTPU6P0+Oy4itgffTUa80B8317sXzfOr1qUzSL29jE7Th11llXiu2haB7B9Glpzo2CDElin+geQ==}
peerDependencies:
react: '>=16.8.0'
react-dom: '>=16.8.0'
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-BG/ETy3eBjFap7+zIti53f0PCLGDzNXyTmn6fSdrudORf+OH04MxrW4p5+mPu4mgMk9kM41iYONjc3DOUWTcfg==}
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-oPZ0JoKtVSK9hVHSBDKG1oCLgnZbpxuH/SMnyDtXkNhn9+SF1+98DlWILFYxIT8faOS/GgfhlNFREmym6oqrEg==}
peerDependencies:
- '@dnd-kit/core': ^6.1.0
+ '@dnd-kit/core': ^6.2.0
react: '>=16.8.0'
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-U3jk5ebVXe1Lr7c2wU7SBZjcWdQP+j7peHJfCspnA81enlu88Mgd7CC8Q+pub9ubP7eKVETzJW+IBAhsqbSu/g==}
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-3/9r8Mmba0nKTbo8kPnVSFZKf/VSy94nXZ3aUwzPEh78j/LooQ/EFKRZENak4PHKBkN53mgTF/z+Sd8H+FcAnQ==}
peerDependencies:
- '@dnd-kit/core': ^6.1.0
+ '@dnd-kit/core': ^6.2.0
react: '>=16.8.0'
'@dnd-kit/[email protected]':
@@ -9645,29 +9645,29 @@ snapshots:
'@dagrejs/[email protected]': {}
dependencies:
react: 18.3.1
tslib: 2.8.1
dependencies:
- '@dnd-kit/accessibility': 3.1.0([email protected])
+ '@dnd-kit/accessibility': 3.1.1([email protected])
'@dnd-kit/utilities': 3.2.2([email protected])
react: 18.3.1
react-dom: 18.3.1([email protected])
tslib: 2.8.1
dependencies:
'@dnd-kit/utilities': 3.2.2([email protected])
react: 18.3.1
tslib: 2.8.1
dependencies:
'@dnd-kit/utilities': 3.2.2([email protected])
react: 18.3.1
tslib: 2.8.1
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index 025f718e28..e1e624d677 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -78,20 +78,6 @@ export const ChatPanel = () => {
setCompletionBody(getAICompletionBody(`${messagesConcat}\n\n${newValue}`));
};
- useEffect(() => {
- if (activeChat) {
- setMessages(
- activeChat.messages.map(({ role, content, timestamp }) => ({
- role,
- content,
- id: timestamp.toString(),
- })),
- );
- setInput("");
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeChat?.id]);
-
const lastMessageText = messages.at(-1)?.content;
useEffect(() => {
if (isLoading) {
@@ -123,6 +109,7 @@ export const ChatPanel = () => {
setCompletionBody(nextCompletionBody);
setMessages([]);
+ setInput("");
append(
{
role: "user",
diff --git a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx
index 4a86c17dfc..6dd0b12e2f 100644
--- a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx
+++ b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx
@@ -11,12 +11,7 @@ import ReactFlow, {
useReactFlow,
} from "reactflow";
-import React, {
- type PropsWithChildren,
- useEffect,
- useMemo,
- useState,
-} from "react";
+import React, { type PropsWithChildren, useEffect, useState } from "react";
import {
EdgeMarkerContext,
nodeTypes,
@@ -57,7 +52,8 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
layoutDirection,
settings,
}) => {
- const initial = useMemo(() => {
+ // eslint-disable-next-line react/hook-use-state
+ const [initial] = useState(() => {
let elements = elementsBuilder.createElements(
cellIds,
cellAtoms,
@@ -70,8 +66,7 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
return elements;
// Only run once
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ });
const [nodes, setNodes, onNodesChange] = useNodesState(initial.nodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initial.edges);
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 23f06ef66f..21a26ae8dc 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -640,6 +640,9 @@ const CellComponent = (
serializedEditorState={serializedEditorState}
runCell={handleRun}
updateCellCode={updateCellCode}
+ setEditorView={(ev) => {
+ editorView.current = ev;
+ }}
createNewCell={createNewCell}
deleteCell={deleteCell}
focusCell={focusCell}
diff --git a/frontend/src/components/editor/SortableCell.tsx b/frontend/src/components/editor/SortableCell.tsx
index 3d4383f0c5..695df2ef9f 100644
--- a/frontend/src/components/editor/SortableCell.tsx
+++ b/frontend/src/components/editor/SortableCell.tsx
@@ -1,12 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
import React, { memo, useContext } from "react";
-import { mergeRefs } from "../../utils/mergeRefs";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { GripVerticalIcon } from "lucide-react";
import type { CellId } from "@/core/cells/ids";
import { cn } from "@/utils/cn";
import { Events } from "@/utils/events";
+import { mergeRefs } from "@/utils/mergeRefs";
interface Props extends React.HTMLAttributes<HTMLDivElement> {
cellId: CellId;
@@ -25,7 +25,10 @@ export const CellDragHandle: React.FC = memo(() => {
CellDragHandle.displayName = "DragHandle";
const SortableCellInternal = React.forwardRef(
- ({ cellId, canMoveX, ...props }: Props, ref: React.Ref<HTMLDivElement>) => {
+ (
+ { cellId, canMoveX, ...props }: Props,
+ ref: React.ForwardedRef<HTMLDivElement>,
+ ) => {
// Sort
const {
attributes,
@@ -50,8 +53,6 @@ const SortableCellInternal = React.forwardRef(
position: "relative",
};
- const mergedRef = mergeRefs<HTMLDivElement>(ref, setNodeRef);
-
const dragHandle = (
<div
{...attributes}
@@ -69,7 +70,9 @@ const SortableCellInternal = React.forwardRef(
return (
<div
tabIndex={-1}
- ref={mergedRef}
+ ref={(r) => {
+ mergeRefs<HTMLDivElement>(ref, setNodeRef)(r);
+ }}
{...props}
data-is-dragging={isDragging}
className={cn(
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 6004e8df26..f128a44a5d 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -30,6 +30,7 @@ import { autoInstantiateAtom, isAiEnabled } from "@/core/config/config";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import { useSplitCellCallback } from "../useSplitCell";
+import { invariant } from "@/utils/invariant";
export interface CellEditorProps
extends Pick<CellRuntimeState, "status">,
@@ -49,6 +50,7 @@ export interface CellEditorProps
theme: Theme;
showPlaceholder: boolean;
editorViewRef: React.MutableRefObject<EditorView | null>;
+ setEditorView: (view: EditorView) => void;
/**
* If true, the cell is allowed to be focus on.
* This is false when the app is initially loading.
@@ -79,6 +81,7 @@ const CellEditorInternal = ({
code,
status,
serializedEditorState,
+ setEditorView,
runCell,
updateCellCode,
createNewCell,
@@ -242,58 +245,62 @@ const CellEditorInternal = ({
setLanguageAdapter,
]);
+ const handleInitializeEditor = useEvent(() => {
+ // Create a new editor
+ const ev = new EditorView({
+ state: EditorState.create({
+ doc: code,
+ extensions: extensions,
+ }),
+ });
+ setEditorView(ev);
+ // Initialize the language adapter
+ switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);
+ });
+
+ const handleReconfigureEditor = useEvent(() => {
+ invariant(editorViewRef.current !== null, "Editor view is not initialized");
+ editorViewRef.current.dispatch({
+ effects: [
+ StateEffect.reconfigure.of([extensions]),
+ reconfigureLanguageEffect(
+ editorViewRef.current,
+ userConfig.completion,
+ new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),
+ ),
+ ],
+ });
+ });
+
+ const handleDeserializeEditor = useEvent(() => {
+ invariant(serializedEditorState, "Editor view is not initialized");
+ const ev = new EditorView({
+ state: EditorState.fromJSON(
+ serializedEditorState,
+ {
+ doc: code,
+ extensions: extensions,
+ },
+ { history: historyField },
+ ),
+ });
+ // Initialize the language adapter
+ switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);
+ setEditorView(ev);
+ // Clear the serialized state so that we don't re-create the editor next time
+ clearSerializedEditorState({ cellId });
+ });
+
useEffect(() => {
- // Should focus will be true if its a newly created editor
- let shouldFocus: boolean;
if (serializedEditorState === null) {
- // If the editor already exists, reconfigure it with the new extensions.
- // Triggered when, e.g., placeholder changes.
if (editorViewRef.current === null) {
- // Otherwise, create a new editor.
- editorViewRef.current = new EditorView({
- state: EditorState.create({
- doc: code,
- extensions: extensions,
- }),
- });
- shouldFocus = true;
- // Initialize the language adapter
- switchLanguage(
- editorViewRef.current,
- getInitialLanguageAdapter(editorViewRef.current.state).type,
- );
+ handleInitializeEditor();
} else {
- editorViewRef.current.dispatch({
- effects: [
- StateEffect.reconfigure.of([extensions]),
- reconfigureLanguageEffect(
- editorViewRef.current,
- userConfig.completion,
- new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),
- ),
- ],
- });
- shouldFocus = false;
+ // If the editor already exists, reconfigure it with the new extensions.
+ handleReconfigureEditor();
}
} else {
- editorViewRef.current = new EditorView({
- state: EditorState.fromJSON(
- serializedEditorState,
- {
- doc: code,
- extensions: extensions,
- },
- { history: historyField },
- ),
- });
- // Initialize the language adapter
- switchLanguage(
- editorViewRef.current,
- getInitialLanguageAdapter(editorViewRef.current.state).type,
- );
- shouldFocus = true;
- // Clear the serialized state so that we don't re-create the editor next time
- clearSerializedEditorState({ cellId });
+ handleDeserializeEditor();
}
if (
@@ -304,7 +311,21 @@ const CellEditorInternal = ({
// Always replace the children in case the editor view was re-created.
editorViewParentRef.current.replaceChildren(editorViewRef.current.dom);
}
+ }, [
+ handleInitializeEditor,
+ handleReconfigureEditor,
+ handleDeserializeEditor,
+ editorViewRef,
+ editorViewParentRef,
+ serializedEditorState,
+ // Props to trigger reconfiguration
+ extensions,
+ ]);
+ // Auto-focus. Should focus newly created editors.
+ const shouldFocus =
+ editorViewRef.current === null || serializedEditorState !== null;
+ useEffect(() => {
if (shouldFocus && allowFocus) {
// Focus and scroll into view; request an animation frame to
// avoid a race condition when new editors are created
@@ -317,23 +338,13 @@ const CellEditorInternal = ({
});
});
}
-
- // We don't want to re-run this effect when `allowFocus` or `code` changes
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- editorViewRef,
- extensions,
- userConfig.completion,
- userConfig.keymap,
- clearSerializedEditorState,
- cellId,
- serializedEditorState,
- ]);
+ }, [shouldFocus, allowFocus, editorViewRef]);
// Destroy the editor when the component is unmounted
useEffect(() => {
+ const ev = editorViewRef.current;
return () => {
- editorViewRef.current?.destroy();
+ ev?.destroy();
};
}, [editorViewRef]);
@@ -343,11 +354,11 @@ const CellEditorInternal = ({
initialPrompt={aiCompletionCell?.initialPrompt}
currentCode={editorViewRef.current?.state.doc.toString() ?? code}
currentLanguageAdapter={languageAdapter}
- declineChange={() => {
+ declineChange={useEvent(() => {
setAiCompletionCell(null);
editorViewRef.current?.focus();
- }}
- onChange={(newCode) => {
+ })}
+ onChange={useEvent((newCode) => {
editorViewRef.current?.dispatch({
changes: {
from: 0,
@@ -355,8 +366,8 @@ const CellEditorInternal = ({
insert: newCode,
},
});
- }}
- acceptChange={(newCode) => {
+ })}
+ acceptChange={useEvent((newCode) => {
editorViewRef.current?.dispatch({
changes: {
from: 0,
@@ -366,7 +377,7 @@ const CellEditorInternal = ({
});
editorViewRef.current?.focus();
setAiCompletionCell(null);
- }}
+ })}
>
<div
className="relative w-full"
@@ -432,7 +443,13 @@ const CellCodeMirrorEditor = React.forwardRef(
return (
<div
className={cn("cm", className)}
- ref={(ref && mergeRefs(ref, internalRef)) || internalRef}
+ ref={(r) => {
+ if (ref) {
+ mergeRefs(ref, internalRef)(r);
+ } else {
+ mergeRefs(internalRef)(r);
+ }
+ }}
data-testid="cell-editor"
/>
);
diff --git a/frontend/src/components/editor/columns/sortable-column.tsx b/frontend/src/components/editor/columns/sortable-column.tsx
index ec7c65aa68..06f8284cfc 100644
--- a/frontend/src/components/editor/columns/sortable-column.tsx
+++ b/frontend/src/components/editor/columns/sortable-column.tsx
@@ -48,8 +48,6 @@ const SortableColumnInternal = React.forwardRef(
"--gutter-width": "50px",
};
- const mergedRef = mergeRefs<HTMLDivElement>(ref, setNodeRef);
-
const { deleteColumn, moveColumn, addColumn } = useCellActions();
const buttonClasses = cn("h-full hover:bg-muted rounded-none");
@@ -129,7 +127,9 @@ const SortableColumnInternal = React.forwardRef(
return (
<div
tabIndex={-1}
- ref={mergedRef}
+ ref={(r) => {
+ mergeRefs(ref, setNodeRef)(r);
+ }}
{...props}
style={style}
data-is-dragging={isDragging}
diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsx
index 62ddf5078a..c7a98e772f 100644
--- a/frontend/src/components/editor/file-tree/file-viewer.tsx
+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx
@@ -71,7 +71,7 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {
internalValueRef.current = internalValue;
useEffect(() => {
return () => {
- if (!data) {
+ if (!data?.contents) {
return;
}
const draft = internalValueRef.current;
@@ -81,7 +81,6 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {
unsavedContentsForFile.set(file.path, draft);
}
};
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [file.path, data?.contents]);
if (error) {
diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsx
index a4b4494230..292e9b0be2 100644
--- a/frontend/src/components/scratchpad/scratchpad.tsx
+++ b/frontend/src/components/scratchpad/scratchpad.tsx
@@ -49,7 +49,7 @@ export const ScratchPad: React.FC = () => {
const notebookState = useNotebook();
const [userConfig] = useUserConfig();
const { theme } = useTheme();
- const ref = useRef<EditorView>(null);
+ const ref = useRef<EditorView | null>(null);
const lastFocusedCellId = useLastFocusedCellId();
const { createNewCell, updateCellCode } = useCellActions();
@@ -147,6 +147,9 @@ export const ScratchPad: React.FC = () => {
clearSerializedEditorState={Functions.NOOP}
userConfig={userConfig}
editorViewRef={ref}
+ setEditorView={(ev) => {
+ ref.current = ev;
+ }}
hidden={false}
temporarilyShowCode={Functions.NOOP}
languageAdapter={languageAdapter}
diff --git a/frontend/src/core/hotkeys/actions.ts b/frontend/src/core/hotkeys/actions.ts
index 68e2b12053..e89da5a405 100644
--- a/frontend/src/core/hotkeys/actions.ts
+++ b/frontend/src/core/hotkeys/actions.ts
@@ -1,6 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { atom, useAtomValue, useSetAtom } from "jotai";
import type { HotkeyAction } from "@/core/hotkeys/hotkeys";
+import useEvent from "react-use-event-hook";
/**
* Map of registered keyboard shortcuts and their callbacks.
@@ -22,14 +23,14 @@ export function useRegisteredActions() {
export function useSetRegisteredAction() {
const set = useSetAtom(registeredActionsAtom);
return {
- registerAction: (shortcut: HotkeyAction, callback: () => void) => {
+ registerAction: useEvent((shortcut: HotkeyAction, callback: () => void) => {
set((actions) => ({ ...actions, [shortcut]: callback }));
- },
- unregisterAction: (shortcut: HotkeyAction) => {
+ }),
+ unregisterAction: useEvent((shortcut: HotkeyAction) => {
set((actions) => {
const { [shortcut]: unused, ...rest } = actions;
return rest;
});
- },
+ }),
};
}
diff --git a/frontend/src/core/wasm/PyodideLoader.tsx b/frontend/src/core/wasm/PyodideLoader.tsx
index 87f549571d..6587a60a63 100644
--- a/frontend/src/core/wasm/PyodideLoader.tsx
+++ b/frontend/src/core/wasm/PyodideLoader.tsx
@@ -19,14 +19,16 @@ export const PyodideLoader: React.FC<PropsWithChildren> = ({ children }) => {
return children;
}
+ return <PyodideLoaderInner>{children}</PyodideLoaderInner>;
+};
+
+const PyodideLoaderInner: React.FC<PropsWithChildren> = ({ children }) => {
// isPyodide() is constant, so this is safe
- // eslint-disable-next-line react-hooks/rules-of-hooks
const { loading, error } = useAsyncData(async () => {
await PyodideBridge.INSTANCE.initialized.promise;
return true;
}, []);
- // eslint-disable-next-line react-hooks/rules-of-hooks
const hasOutput = useAtomValue(hasAnyOutputAtom);
if (loading) {
diff --git a/frontend/src/hooks/useAsyncData.ts b/frontend/src/hooks/useAsyncData.ts
index d65fd2b191..ea2485ad5d 100644
--- a/frontend/src/hooks/useAsyncData.ts
+++ b/frontend/src/hooks/useAsyncData.ts
@@ -1,6 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { SetStateAction } from "jotai";
import { type DependencyList, useState, useEffect, type Dispatch } from "react";
+import useEvent from "react-use-event-hook";
interface AsyncDataResponse<T> {
data: T | undefined;
@@ -55,6 +56,8 @@ export function useAsyncData<T>(
? { fetch: loaderOrProps }
: loaderOrProps;
+ const fetchStable = useEvent(asProps.fetch);
+
useEffect(() => {
let isCancelled = false;
let keepPrevious = false;
@@ -64,8 +67,7 @@ export function useAsyncData<T>(
},
};
setLoading(true);
- asProps
- .fetch(context)
+ fetchStable(context)
.then((data) => {
if (isCancelled) {
return;
@@ -92,8 +94,7 @@ export function useAsyncData<T>(
return () => {
isCancelled = true;
};
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [...deps, nonce]);
+ }, [...deps, nonce, fetchStable]);
return {
data,
diff --git a/frontend/src/hooks/useHotkey.ts b/frontend/src/hooks/useHotkey.ts
index 54042196c5..48f9140944 100644
--- a/frontend/src/hooks/useHotkey.ts
+++ b/frontend/src/hooks/useHotkey.ts
@@ -49,8 +49,7 @@ export function useHotkey(shortcut: HotkeyAction, callback: HotkeyHandler) {
registerAction(shortcut, memoizeCallback);
return () => unregisterAction(shortcut);
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [memoizeCallback, shortcut, isNOOP]);
+ }, [memoizeCallback, shortcut, isNOOP, registerAction, unregisterAction]);
}
/**
diff --git a/frontend/src/hooks/useScript.ts b/frontend/src/hooks/useScript.ts
index 1ce1845f6b..d89d8f0300 100644
--- a/frontend/src/hooks/useScript.ts
+++ b/frontend/src/hooks/useScript.ts
@@ -84,8 +84,7 @@ export function useScript(
}
setStatus("unknown");
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [src]);
+ }, [src, options.removeOnUnmount]);
return status;
}
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index d5ebaf2d35..0fe2115afc 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -219,6 +219,7 @@ export const LoadingDataTableComponent = memo(
props: Omit<DataTableProps<T>, "sorting"> & { data: TableData<T> },
) => {
const search = props.search;
+ const setValue = props.setValue;
// Sorting/searching state
const [sorting, setSorting] = useState<SortingState>([]);
const [paginationState, setPaginationState] =
@@ -234,9 +235,8 @@ export const LoadingDataTableComponent = memo(
// so we can't rely on the data to be the same
// We can remove this when we have a stable key for each row
useEffect(() => {
- props.setValue([]);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [props.setValue, filters, searchQuery, sorting]);
+ setValue([]);
+ }, [setValue, filters, searchQuery, sorting]);
// If pageSize changes, reset pagination state
useEffect(() => {
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index a7d8b47009..0cc050a7fa 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -167,10 +167,10 @@ const LoadedSlot = ({
}, [widget]);
// When the value changes, update the model
+ const valueMemo = useDeepCompareMemoize(value);
useEffect(() => {
- model.current.updateAndEmitDiffs(value);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [useDeepCompareMemoize([value])]);
+ model.current.updateAndEmitDiffs(valueMemo);
+ }, [valueMemo]);
return <div ref={ref} />;
};
diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
index f1af33b4d5..574a81a8e4 100644
--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
@@ -119,11 +119,10 @@ export const PlotlyComponent = memo(
useEffect(() => {
const nextFigure = structuredClone(originalFigure);
setFigure(nextFigure);
- setLayout({
+ setLayout((prev) => ({
...initialLayout(nextFigure),
- ...value,
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ ...prev,
+ }));
}, [originalFigure, isScriptLoaded]);
const [layout, setLayout] = useState<Partial<Plotly.Layout>>(() => {
@@ -141,6 +140,7 @@ export const PlotlyComponent = memo(
setValue({});
});
+ const configMemo = useDeepCompareMemoize(config);
const plotlyConfig = useMemo((): Partial<Plotly.Config> => {
return {
displaylogo: false,
@@ -161,10 +161,9 @@ export const PlotlyComponent = memo(
},
],
// Prioritize user's config
- ...config,
+ ...configMemo,
};
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [handleReset, useDeepCompareMemoize(config)]);
+ }, [handleReset, configMemo]);
const prevFigure = usePrevious(figure) ?? figure;
diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx
index 4bdab62dc2..935b035ca2 100644
--- a/frontend/src/plugins/impl/vega/vega-component.tsx
+++ b/frontend/src/plugins/impl/vega/vega-component.tsx
@@ -6,7 +6,6 @@ import { getSelectionParamNames, ParamNames } from "./params";
import type { VegaLiteSpec } from "./types";
import { Alert, AlertTitle } from "@/components/ui/alert";
import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
-import { useDebugMounting, usePropsDidChange } from "@/hooks/debug";
import { debounce } from "lodash-es";
import useEvent from "react-use-event-hook";
import { Logger } from "@/utils/Logger";
@@ -90,24 +89,14 @@ const LoadedVegaComponent = ({
const vegaView = useRef<View>();
const [error, setError] = useState<Error>();
- // Debug
- useDebugMounting("VegaComponent");
- usePropsDidChange("VegaComponent", {
- value,
- setValue,
- chartSelection,
- fieldSelection,
- spec,
- });
-
// Aggressively memoize the spec, so Vega doesn't re-render/re-mount the component
+ const specMemo = useDeepCompareMemoize(spec);
const selectableSpec = useMemo(() => {
- return makeSelectable(fixRelativeUrl(spec), {
+ return makeSelectable(fixRelativeUrl(specMemo), {
chartSelection,
fieldSelection,
});
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [useDeepCompareMemoize(spec), chartSelection, fieldSelection]);
+ }, [specMemo, chartSelection, fieldSelection]);
const names = useMemo(
() => getSelectionParamNames(selectableSpec),
[selectableSpec],
@@ -119,9 +108,10 @@ const LoadedVegaComponent = ({
setValue({ ...value, ...newValue });
});
+ const namesMemo = useDeepCompareMemoize(names);
const signalListeners = useMemo(
() =>
- names.reduce<SignalListeners>((acc, name) => {
+ namesMemo.reduce<SignalListeners>((acc, name) => {
// pan/zoom does not count towards selection
if (ParamNames.PAN_ZOOM === name) {
return acc;
@@ -140,8 +130,7 @@ const LoadedVegaComponent = ({
}, 100);
return acc;
}, {}),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [useDeepCompareMemoize(names), setValue],
+ [namesMemo, handleUpdateValue],
);
const handleError = useEvent((error) => {
diff --git a/frontend/src/utils/mergeRefs.ts b/frontend/src/utils/mergeRefs.ts
index 6c5120918f..2c6c08fd06 100644
--- a/frontend/src/utils/mergeRefs.ts
+++ b/frontend/src/utils/mergeRefs.ts
@@ -1,5 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
-export function mergeRefs<T>(...refs: Array<React.Ref<T>>): React.Ref<T> {
+export function mergeRefs<T>(
+ ...refs: Array<React.Ref<T>>
+): (value: T | null) => void {
return (value) => {
refs.forEach((ref) => {
if (typeof ref === "function") {
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 922f86303a..59514edeb6 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -20,6 +20,14 @@ const htmlDevPlugin = (): Plugin => {
return html;
}
+ // Add react-scan in dev mode
+ if (isDev) {
+ html = html.replace(
+ "<head>",
+ '<head>\n<script src="https://unpkg.com/react-scan/dist/auto.global.js"></script>',
+ );
+ }
+
if (isPyodide) {
const modeFromUrl = ctx.originalUrl?.includes("mode=read")
? "read"