Sub topic 4
Updating state immutably with patchState
This chapter covers how a signal store changes its state. It assumes you know Angular signals (signal, computed, effect), TypeScript object types and spreads, and the basics of signalStore and withState from the previous chapters.
Why state changes go through patchState
A signal store keeps its state in signals. Each top-level property of the state becomes a read-only signal on the store. The store does not expose set or update on those signals, so a component cannot write store.filter.set('open'). The only supported way to change state is the patchState function.
This gives you one entry point for every write. When you search a codebase for patchState, you find every place state can change.
import { patchState } from '@ngrx/signals';patchState takes the store (or a state source) as its first argument. After that it takes one or more updates. Each update is either a partial state object or an updater function.
The two forms of an update
A partial state object
Pass an object with the properties you want to replace. Properties you leave out keep their current values.
patchState(store, { filter: 'open' });This is a shallow merge at the top level. filter gets the new value, and todos stays untouched.
An updater function
Pass a function that receives the current state and returns a partial state. Use this form when the new value depends on the old one.
patchState(store, (state) => ({
todos: [...state.todos, { id: Date.now(), title: 'Write docs', done: false }],
}));The function must return a new object. It should not modify state.
Several updates in one call
You can pass any number of updates. They run in order, and the later ones see the result of the earlier ones.
patchState(
store,
{ loading: true },
(state) => ({ todos: state.todos.filter((t) => !t.done) }),
{ loading: false },
);All updates in one call are applied together. Signals notify consumers once for the combined change, not once per update. Listing updates in one call is therefore better than calling patchState three times in a row when the changes belong together.
What "immutable" means here
Immutable means you never modify an existing object or array. You build a new one that contains the changes. The old value stays as it was.
This matters because signals decide whether something changed by comparing references. If you mutate an array in place, the reference is the same, so the signal sees no change. Computed signals and templates that depend on it do not update.
The rules for state updates:
| Task | Mutating (avoid) | Immutable (use) |
|---|---|---|
| Add to an array | `state.todos.push(t)` | `[...state.todos, t]` |
| Remove from an array | `state.todos.splice(i, 1)` | `state.todos.filter((x) => x.id !== id)` |
| Change one item | `todo.done = true` | `state.todos.map((x) => x.id === id ? { ...x, done: true } : x)` |
| Change an object property | `state.user.name = 'Ana'` | `{ user: { ...state.user, name: 'Ana' } }` |
| Sort an array | `state.todos.sort(...)` | `[...state.todos].sort(...)` |
In development builds, SignalStore freezes state objects deeply. If you try to mutate them, you get a runtime error in strict mode. The error is a useful safety net, but do not depend on it. Production builds may skip the check.
A complete example
The store below comes from the earlier chapters. It shows patchState used in each of its forms.
import { computed } from '@angular/core';
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals';
type Filter = 'all' | 'open' | 'done';
type Todo = { id: number; title: string; done: boolean };
type TodosState = { todos: Todo[]; filter: Filter };
const initialState: TodosState = { todos: [], filter: 'all' };
export const TodosStore = signalStore(
{ providedIn: 'root' },
withState(initialState),
withComputed(({ todos, filter }) => {
const openCount = computed(() => todos().filter((t) => !t.done).length);
const visibleTodos = computed(() => {
switch (filter()) {
case 'open':
return todos().filter((t) => !t.done);
case 'done':
return todos().filter((t) => t.done);
default:
return todos();
}
});
return { openCount, visibleTodos };
}),
withMethods((store) => ({
add(title: string): void {
patchState(store, (state) => ({
todos: [...state.todos, { id: Date.now(), title, done: false }],
}));
},
toggle(id: number): void {
patchState(store, (state) => ({
todos: state.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
}));
},
setFilter(filter: Filter): void {
patchState(store, { filter });
},
})),
);Look at each method:
adduses the updater form because the new array depends on the current one. The spread creates a new array that ends with the new todo.toggleusesmap. Every todo except the matching one is returned as is, so those objects keep their identity. Only the matching todo is copied with{ ...t, done: !t.done }.setFilteruses the object form because the new value does not depend on the old one.
Keeping the identity of unchanged items is a real benefit. Angular's @for with track todo.id and any computed that compares items by reference can skip work for the todos that did not change.
How patchState reaches the store
Inside withMethods, the store argument is a writable state source. That is why patchState(store, ...) compiles there. Outside the store, for example in a component, the injected store is not writable by default. A component cannot call patchState(this.store, ...) on a store whose state is protected.
This is deliberate. State is encapsulated, and components change it only through the methods you expose. If you need a component to write directly, you would have to opt out of that protection, but doing so gives up the single-entry-point guarantee. The method-based approach is the better default.
import { Component, inject } from '@angular/core';
import { TodosStore } from './todos.store';
@Component({
selector: 'app-todos',
template: `
<p>{{ store.openCount() }} open</p>
@for (todo of store.visibleTodos(); track todo.id) {
<label>
<input type="checkbox" [checked]="todo.done" (change)="store.toggle(todo.id)" />
{{ todo.title }}
</label>
}
`,
})
export class TodosComponent {
readonly store = inject(TodosStore);
}The component only calls store.toggle(...). It never sees patchState.
Updating nested state
patchState merges only the top level. If your state has a nested object, replacing one property of it means you must rebuild the object.
type SettingsState = {
user: { name: string; address: { city: string; zip: string } };
theme: 'light' | 'dark';
};To change only the city, copy each level on the path:
patchState(store, (state) => ({
user: {
...state.user,
address: { ...state.user.address, city: 'Lisbon' },
},
}));If you write { user: { address: { city: 'Lisbon' } } }, you replace user entirely. The name and zip properties are lost, and TypeScript will report the missing properties.
Deep nesting makes these spreads long. Two things help. Keep state flat when you can, with separate top-level properties instead of one deep tree. For collections, use withEntities, which a later chapter covers.
Reusable updaters
An updater is just a function from state to a partial state. You can write it once and share it. This keeps the shape of updates consistent across stores.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
type CounterState = { count: number };
const increment = (by = 1) => (state: CounterState) => ({ count: state.count + by });
const reset = () => ({ count: 0 });
export const CounterStore = signalStore(
withState<CounterState>({ count: 0 }),
withMethods((store) => ({
increment(by = 1): void {
patchState(store, increment(by));
},
reset(): void {
patchState(store, reset());
},
})),
);Here increment and reset are plain functions that can be tested alone and reused. This pattern is how the entity updaters (addEntity, updateEntity, and others) work. They are functions you pass to patchState.
Common errors
Mutating inside the updater
// Wrong: pushes into the existing array and returns the same reference
patchState(store, (state) => {
state.todos.push(newTodo);
return { todos: state.todos };
});The reference did not change, and the frozen state may throw. Use a spread.
Forgetting that patchState is synchronous
patchState applies the change immediately. After the call returns, reading the signal gives the new value. It does not wait for a microtask or a change detection run.
patchState(store, { filter: 'done' });
console.log(store.filter()); // 'done'Updating after an asynchronous call with stale state
If you read state before an await and patch afterwards, you might overwrite changes made in between.
async function refresh(store: { todos: () => Todo[] }) {
const current = store.todos(); // read now
const extra = await fetchExtra();
// `current` may be out of date here
patchState(store as any, { todos: [...current, ...extra] });
}Use the updater form after the await so you work from the latest state:
patchState(store, (state) => ({ todos: [...state.todos, ...extra] }));Patching a property that is not in the state
TypeScript checks the partial state against the store's state type. A typo such as { fliter: 'open' } is a compile error. Do not cast around the error with as any, because it removes the protection.
Using a non-serializable or class instance value
patchState works with any value, but the freeze and shallow-comparison behavior assume plain objects and arrays. Class instances, Map and Set are poor fits. A Map changed in place looks unchanged. Prefer plain objects and arrays, or copy the Map when you change it.
Choosing between the two forms
| Situation | Form to use |
|---|---|
| New value does not depend on current state | Object: `patchState(store, { filter })` |
| New value is computed from current state | Updater function |
| Several related changes that should notify once | Multiple updates in one call |
| Same change used in many places | A named, reusable updater function |
Summary of the rules
- Write all state changes with
patchState, inside store methods. - Return new objects and arrays. Never modify the existing ones.
- Use the updater form whenever the new value depends on the old one.
- Copy every level of a nested path you change.
- Group related changes into one
patchStatecall.
Exercise
A store has the state { cart: { items: string[]; coupon: string | null } }. Write a method body that adds the item 'book' to cart.items without losing the current coupon. Explain why patchState(store, { cart: { items: ['book'] } }) is wrong.
Show answer
Use the updater form and copy each level: patchState(store, (state) => ({ cart: { ...state.cart, items: [...state.cart.items, 'book'] } }));. The object { cart: { items: ['book'] } } replaces the whole cart value. It drops coupon, and it also discards the items already in the cart. TypeScript reports the missing coupon property. patchState merges only the top level, so nested objects must be rebuilt with spreads.
Exercise
You call patchState three times in a row inside one method: first { loading: true }, then a todos update, then { loading: false }. How can you change the code so consumers are notified once, and why does the order of updates still matter?
Show answer
Pass all three updates to a single call: patchState(store, { loading: true }, (state) => ({ todos: ... }), { loading: false });. The updates are applied in order and the signals notify once for the combined change. The order matters because each later update sees the result of the earlier ones, and a later update overwrites an earlier one that sets the same property.