Compare reactive stores and effects
Use named pulse commits, direct mutable state and a tracked reactive effect.
Table of contents
APIs used
- mount
- Starts a Valyrian.js application on a DOM target.
- createEffect
- Runs work in response to reactive dependencies.
- createMutableStore
- Creates a mutable store with named pulse methods.
- createPulseStore
- Returns proxied state and named pulse methods that publish committed changes.
Run this recipe
- Starting project
- Use the local TSX and ESM project from Stage 1 with Valyrian.js installed and its ESM browser build configured.
- File
- Replace src/client-entry.tsx with this recipe snippet.
- Run
- Run npm run build, serve public with npx --yes serve@14.2.5 public --listen 8000, open http://localhost:8000 and use the example's visible controls.
- Observable result
- The view displays Count: 2, mode: published and the effect values observed before and after the commits.
Starting point
Create an immutable pulse store, a mutable store and an effect that reads both.
Steps
Write directly to mutable public state, call named methods on both stores and wait for their debounced subscriber pass before rendering the result.
tsimport { mount } from "valyrian.js";
import {
createEffect,
createMutableStore,
createPulseStore,
} from "valyrian.js/pulses";
const counter = createPulseStore(
{ count: 0 },
{
increment(state, amount = 1) {
state.count += amount;
},
},
);
const editor = createMutableStore(
{ mode: "draft" },
{
publish(state) {
state.mode = "published";
},
},
);
const observed: string[] = [];
const dispose = createEffect(() => {
observed.push(`${counter.state.count}:${editor.state.mode}`);
});
editor.state.mode = "editing";
counter.increment(2);
editor.publish();
await new Promise((resolve) => setTimeout(resolve, 0));
mount(
"body",
() =>
`Count: ${counter.state.count}; mode: ${editor.state.mode}; effect: ${observed.join(" -> ")}`,
);
dispose();Result
The view displays Count: 2, mode: published and the effect values observed before and after the commits.
Limits
createPulseStore commits through named pulses. createMutableStore accepts direct public writes, but a direct write does not notify by itself. createEffect runs immediately, replaces dependencies on each run and stops after dispose().