Store utilities

produce

Edit this page

produce is an Immer inspired API for Solid's Store objects that allows the store to be mutated using a draft pattern.

import { produce } from "solid-js/store"
import type { NotWrappable, Store } from "solid-js/store"
function produce<T>(
fn: (state: T) => void
): (
state: T extends NotWrappable ? T : Store<T>
) => T extends NotWrappable ? T : Store<T>;

Default Setter in Solid 2.0

In Solid 2.0, the store setter already receives a mutable draft. The following two patterns are equivalent:

import { createStore, produce } from "solid-js/store";
const [state, setState] = createStore({
user: {
name: "John",
age: 30,
},
list: ["book", "pen"],
});
// Solid 2.0: draft-first setter (preferred -- no produce wrapper needed)
setState((draft) => {
draft.user.name = "Jane";
draft.list.push("pencil");
});
// Equivalent using explicit produce (still works, but redundant for setStore)
setState(
produce((state) => {
state.user.name = "Jane";
state.list.push("pencil");
})
);

Standalone Use

The produce utility is still useful when you need to create a reusable modifier function outside of setStore, or when working with other APIs that accept store modifiers:

import { produce } from "solid-js/store";
// Create a reusable modifier
const addItem = (item: string) =>
produce((state) => {
state.list.push(item);
});
// Apply it later
setState(addItem("pencil"));
Report an issue with this page