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.

fix: cache reducer action creation (#2020)

Myles Scolnick203cc7fe2eb0
diff --git a/frontend/src/utils/__tests__/createReducer.test.ts b/frontend/src/utils/__tests__/createReducer.test.ts
new file mode 100644
index 0000000000..69c2dec29b
--- /dev/null
+++ b/frontend/src/utils/__tests__/createReducer.test.ts
@@ -0,0 +1,141 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect, vi } from "vitest";
+import { Logger } from "@/utils/Logger";
+import { createReducer, createReducerAndAtoms } from "../createReducer";
+
+interface State {
+ count: number;
+}
+
+describe("createReducer", () => {
+ it("should create a reducer and actions", () => {
+ const initialState = () => ({ count: 0 });
+ const reducers = {
+ increment: (state: State, payload: number) => ({
+ count: state.count + payload,
+ }),
+ decrement: (state: State, payload: number) => ({
+ count: state.count - payload,
+ }),
+ };
+
+ const { reducer, createActions } = createReducer(initialState, reducers);
+
+ const dispatch = vi.fn();
+ const actions = createActions(dispatch);
+
+ expect(typeof reducer).toBe("function");
+ expect(typeof actions.increment).toBe("function");
+ expect(typeof actions.decrement).toBe("function");
+
+ actions.increment(5);
+ expect(dispatch).toHaveBeenCalledWith({ type: "increment", payload: 5 });
+
+ actions.decrement(3);
+ expect(dispatch).toHaveBeenCalledWith({ type: "decrement", payload: 3 });
+ });
+
+ it("actions are the same reference", () => {
+ const initialState = () => ({ count: 0 });
+ const reducers = {
+ increment: (state: State, payload: number) => ({
+ count: state.count + payload,
+ }),
+ };
+
+ const { createActions } = createReducer(initialState, reducers);
+ const actions = createActions(vi.fn());
+
+ expect(actions.increment).toBe(actions.increment);
+ });
+
+ it("can destructure actions", () => {
+ const initialState = () => ({ count: 0 });
+ const reducers = {
+ increment: (state: State, payload: number) => ({
+ count: state.count + payload,
+ }),
+ };
+
+ const { createActions } = createReducer(initialState, reducers);
+
+ const dispatch = vi.fn();
+ const { increment } = createActions(dispatch);
+
+ expect(typeof increment).toBe("function");
+
+ increment(5);
+ expect(dispatch).toHaveBeenCalledWith({ type: "increment", payload: 5 });
+ });
+
+ it("should handle undefined state", () => {
+ const initialState = () => ({ count: 0 });
+ const reducers = {
+ increment: (state: State, payload: number) => ({
+ count: state.count + payload,
+ }),
+ };
+
+ const { reducer } = createReducer(initialState, reducers);
+
+ const newState = reducer(undefined as unknown as State, {
+ type: "increment",
+ payload: 5,
+ });
+ expect(newState).toEqual({ count: 5 });
+ });
+
+ it("should log error for undefined action type", () => {
+ const initialState = () => ({ count: 0 });
+ const reducers = {};
+
+ const { reducer } = createReducer(initialState, reducers);
+ const loggerSpy = vi.spyOn(Logger, "error");
+
+ const state = { count: 0 };
+ const newState = reducer(state, { type: "nonexistent", payload: null });
+
+ expect(newState).toBe(state);
+ expect(loggerSpy).toHaveBeenCalledWith(
+ "Action type nonexistent is not defined in reducers.",
+ );
+ });
+});
+
+describe("createReducerAndAtoms", () => {
+ it("should create reducer, actions, and atoms", () => {
+ const initialState = () => ({ count: 0 });
+ const reducers = {
+ increment: (state: State, payload: number) => ({
+ count: state.count + payload,
+ }),
+ };
+
+ const result = createReducerAndAtoms(initialState, reducers);
+
+ expect(typeof result.reducer).toBe("function");
+ expect(typeof result.createActions).toBe("function");
+ expect(typeof result.valueAtom).toBe("object");
+ expect(typeof result.useActions).toBe("function");
+ });
+
+ it("should apply middleware", () => {
+ const initialState = () => ({ count: 0 });
+ const reducers = {
+ increment: (state: State, payload: number) => ({
+ count: state.count + payload,
+ }),
+ };
+ const middleware = vi.fn();
+
+ const { reducer } = createReducerAndAtoms(initialState, reducers, [
+ middleware,
+ ]);
+
+ const state = { count: 0 };
+ const action = { type: "increment", payload: 5 };
+ reducer(state, action);
+
+ expect(middleware).toHaveBeenCalledWith(state, { count: 5 }, action);
+ });
+});
diff --git a/frontend/src/utils/createReducer.ts b/frontend/src/utils/createReducer.ts
index 270e8ca463..db23265c1b 100644
--- a/frontend/src/utils/createReducer.ts
+++ b/frontend/src/utils/createReducer.ts
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Logger } from "@/utils/Logger";
-import { NoInfer } from "@tanstack/react-table";
+import type { NoInfer } from "@tanstack/react-table";
import { atom, useSetAtom } from "jotai";
-import { Reducer, useMemo } from "react";
+import type { Reducer } from "react";
interface ReducerAction<T> {
type: string;
@@ -51,9 +51,9 @@ export function createReducer<
state = state || initialState();
if (action.type in reducers) {
return reducers[action.type](state, action.payload);
- } else {
- Logger.error(`Action type ${action.type} is not defined in reducers.`);
}
+
+ Logger.error(`Action type ${action.type} is not defined in reducers.`);
return state;
},
createActions: (dispatch: Dispatch) => {
@@ -95,16 +95,23 @@ export function createReducerAndAtoms<
};
const valueAtom = atom(initialState());
+ // map of SetAtom => Actions
+ const actionsMap = new WeakMap();
function useActions() {
const setState = useSetAtom(valueAtom);
- return useMemo(() => {
- const actions = createActions((action) => {
- setState((state) => reducerWithMiddleware(state, action));
- });
- return actions;
- }, [setState]);
+ if (!actionsMap.has(setState)) {
+ actionsMap.set(
+ setState,
+ createActions((action) => {
+ setState((state) => reducerWithMiddleware(state, action));
+ }),
+ );
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ return actionsMap.get(setState)!;
}
return {