Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/proud-bananas-do.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
'@xstate/store': minor
---

Added support for effect-only transitions that don't trigger state updates. Now, when a transition returns the same state but includes effects, subscribers won't be notified of a state change, but the effects will still be executed. This helps prevent unnecessary re-renders while maintaining side effect functionality.

```ts
it('should not trigger update if the snapshot is the same even if there are effects', () => {
const store = createStore({
context: { count: 0 },
on: {
doNothing: (ctx, _, enq) => {
enq.effect(() => {
// …
});
return ctx; // Context is the same, so no update is triggered
// This is the same as not returning anything (void)
}
}
});

const spy = vi.fn();
store.subscribe(spy);

store.trigger.doNothing();
store.trigger.doNothing();

expect(spy).toHaveBeenCalledTimes(0);
});
```
79 changes: 24 additions & 55 deletions packages/xstate-store/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
ExtractEvents,
InteropSubscribable,
Observer,
Recipe,
Store,
StoreAssigner,
StoreContext,
Expand All @@ -28,20 +27,6 @@ const symbolObservable: typeof Symbol.observable = (() =>
(typeof Symbol === 'function' && Symbol.observable) ||
'@@observable')() as any;

/**
* Updates a context object using a recipe function.
*
* @param context - The current context
* @param recipe - A function that describes how to update the context
* @returns The updated context
*/
function setter<TContext extends StoreContext>(
context: TContext,
recipe: Recipe<TContext, TContext>
): TContext {
return recipe(context);
}

const inspectionObservers = new WeakMap<
Store<any, any, any>,
Set<Observer<StoreInspectionEvent>>
Expand Down Expand Up @@ -76,20 +61,25 @@ function createStoreCore<
const transition = logic.transition;

function receive(event: StoreEvent) {
let effects: StoreEffect<TEmitted>[];
[currentSnapshot, effects] = transition(currentSnapshot, event);
const [nextSnapshot, effects] = transition(currentSnapshot, event);

inspectionObservers.get(store)?.forEach((observer) => {
observer.next?.({
type: '@xstate.snapshot',
event,
snapshot: currentSnapshot,
snapshot: nextSnapshot,
actorRef: store,
rootId: store.sessionId
});
});

atom.set(currentSnapshot);
if (nextSnapshot === currentSnapshot && !effects.length) {
return;
}

currentSnapshot = nextSnapshot;

atom.set(nextSnapshot);

for (const effect of effects) {
if (typeof effect === 'function') {
Expand Down Expand Up @@ -423,7 +413,7 @@ export function createStoreTransition<
event: ExtractEvents<TEventPayloadMap>
): [StoreSnapshot<TContext>, StoreEffect<TEmitted>[]] => {
type StoreEvent = ExtractEvents<TEventPayloadMap>;
let currentContext = snapshot.context;
const currentContext = snapshot.context;
const assigner = transitions?.[event.type as StoreEvent['type']];
const effects: StoreEffect<TEmitted>[] = [];

Expand All @@ -447,43 +437,22 @@ export function createStoreTransition<
return [snapshot, effects];
}

if (typeof assigner === 'function') {
currentContext = producer
? producer(currentContext, (draftContext) =>
(assigner as StoreProducerAssigner<TContext, StoreEvent, TEmitted>)(
draftContext,
event,
enqueue
)
const nextContext = producer
? producer(currentContext, (draftContext) =>
(assigner as StoreProducerAssigner<TContext, StoreEvent, TEmitted>)(
draftContext,
event,
enqueue
)
: setter(currentContext, (draftContext) =>
Object.assign(
{},
currentContext,
assigner?.(
draftContext,
event as any, // TODO: help me
enqueue
)
)
);
} else {
const partialUpdate: Record<string, unknown> = {};
for (const key of Object.keys(assigner)) {
const propAssignment = assigner[key];
partialUpdate[key] =
typeof propAssignment === 'function'
? (propAssignment as StoreAssigner<TContext, StoreEvent, TEmitted>)(
currentContext,
event,
enqueue
)
: propAssignment;
}
currentContext = Object.assign({}, currentContext, partialUpdate);
}
)
: (assigner(currentContext, event as any, enqueue) ?? currentContext);

return [{ ...snapshot, context: currentContext }, effects];
return [
nextContext === currentContext
? snapshot
: { ...snapshot, context: nextContext },
effects
];
};
}

Expand Down
2 changes: 0 additions & 2 deletions packages/xstate-store/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ export type ExtractEvents<T extends EventPayloadMap> = Values<{
[K in keyof T & string]: T[K] & { type: K };
}>;

export type Recipe<T, TReturn> = (state: T) => TReturn;

type AllKeys<T> = T extends any ? keyof T : never;

type EmitterFunction<TEmittedEvent extends EventObject> = (
Expand Down
76 changes: 76 additions & 0 deletions packages/xstate-store/test/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,43 @@ it('effects can be enqueued', async () => {
expect(store.getSnapshot().context.count).toEqual(0);
});

it('effect-only transitions should execute effects', () => {
const spy = vi.fn();
const store = createStore({
context: { count: 0 },
on: {
justEffect: (ctx, _, enq) => {
enq.effect(spy);
}
}
});

store.trigger.justEffect();

expect(spy).toHaveBeenCalledTimes(1);
});

it('emits-only transitions should emit events', () => {
const spy = vi.fn();
const store = createStore({
context: { count: 0 },
emits: {
emitted: () => {}
},
on: {
justEmit: (ctx, _, enq) => {
enq.emit.emitted();
}
}
});

store.on('emitted', spy);

store.trigger.justEmit();

expect(spy).toHaveBeenCalledTimes(1);
});

describe('store.trigger', () => {
it('should allow triggering events with a fluent API', () => {
const store = createStore({
Expand Down Expand Up @@ -766,6 +803,45 @@ it('can be created with a logic object', () => {
store.getSnapshot().context.count satisfies string;
});

it('should not trigger update if the snapshot is the same', () => {
Copy link
Collaborator

@Andarist Andarist Jul 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note this diverges from XState too:

import { createActor, createMachine } from "xstate";

const m = createMachine({
  on: {
    FOO: {
      actions: () => {},
    },
  },
});

const a = createActor(m).start();

let s = a.getSnapshot();

a.subscribe((_s) => {
  console.log("next", s === _s, _s);
  s = _s;
});

a.send({ type: "FOO" });
a.send({ type: "FOO" });
a.send({ type: "FOO" });

With the above we get:
Screenshot 2025-07-07 at 08 56 07

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about this behavior? If only actions/effects occur (invisible to the state, at least right now), then the state is going to be exactly the same. But I guess that's the responsibility of the consumer to "filter"

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly here, I think it would be totally OK to filter those out - but I think it would be great if this could be consistent between XState libraries.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I think in XState v6, the purpose of the observer is to observe snapshot changes, so notifying on the same snapshot isn't useful.

const store = createStore({
context: { count: 0 },
on: {
doNothing: (ctx) => ctx
}
});

const spy = vi.fn();
store.subscribe(spy);

store.trigger.doNothing();
store.trigger.doNothing();

expect(spy).toHaveBeenCalledTimes(0);
});

it('should not trigger update if the snapshot is the same even if there are effects', () => {
const store = createStore({
context: { count: 0 },
on: {
doNothing: (ctx, _, enq) => {
enq.effect(() => {
// …
});
return ctx;
}
}
});

const spy = vi.fn();
store.subscribe(spy);

store.trigger.doNothing();
store.trigger.doNothing();

expect(spy).toHaveBeenCalledTimes(0);
});

describe('types', () => {
it('AnyStoreConfig', () => {
function transformStoreConfig(_config: AnyStoreConfig): void {}
Expand Down