Sub topic 4
Updating state immutably with patchState
This chapter assumes you know Angular signals, TypeScript object types, and the signalStore, withState and withMethods functions from the earlier chapters.
What patchState does
patchState is the only supported way to change the state of a signal store. It takes the store and one or more updates. Each update is either a partial state object or a function that receives the current state and returns a partial state object.
patchState shallow-merges each update into the current state. Only the top-level keys you return are replaced. Keys you leave out keep their values. Every changed key gets a new value, so the signals that depend on it notify their readers.
Two forms of update
Use a partial object when the new value does not depend on the old one. Use an updater function when it does.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
type Todo = { id: number; title: string; done: boolean };
type State = { todos: Todo[]; filter: 'all' | 'open' | 'done' };
export const TodosStore = signalStore(
{ providedIn: 'root' },
withState<State>({ todos: [], filter: 'all' }),
withMethods((store) => ({
setFilter(filter: State['filter']): void {
patchState(store, { filter });
},
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 passes an object. add and toggle pass functions because the new todos array is built from the current one.
Why immutability matters
A signal decides whether it changed by comparing the old and new value with Object.is. If you mutate an array with push and put the same array back, the reference is identical, so dependents such as computed signals and templates never update. Creating a new array or object gives a new reference, and the change propagates.
| Goal | Mutating (wrong) | Immutable (right) |
|---|---|---|
| Append an item | `todos.push(x)` | `[...todos, x]` |
| Change one item | `todos[i].done = true` | `todos.map(t => t.id === id ? { ...t, done: true } : t)` |
| Remove an item | `todos.splice(i, 1)` | `todos.filter(t => t.id !== id)` |
Recent NgRx versions also freeze state objects in development mode, so an accidental mutation throws an error instead of failing silently.
Nested state needs a manual spread
Because the merge is shallow, returning a partial nested object replaces the whole nested object.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
type SettingsState = {
user: { name: string; theme: 'light' | 'dark'; language: string };
};
export const SettingsStore = signalStore(
withState<SettingsState>({
user: { name: 'Ada', theme: 'light', language: 'en' },
}),
withMethods((store) => ({
setTheme(theme: 'light' | 'dark'): void {
// Wrong: patchState(store, { user: { theme } }) would drop name and language.
patchState(store, (state) => ({ user: { ...state.user, theme } }));
},
})),
);The commented line would not even compile here, since name and language are required. With optional fields it compiles and silently deletes data, so always spread the nested object.
Applying several updates at once
patchState accepts any number of updates, applied in order. This is how reusable updaters, such as the entity updaters in a later chapter, combine with your own changes.
const setLoading = () => ({ loading: true, error: null });
patchState(store, setLoading(), { query: 'ada' });Passing several updates to one call produces a single state change, so readers do not see an intermediate state.
Common errors
- Mutating
stateinside an updater function and returning it. The reference does not change, so nothing updates. - Forgetting to spread a nested object, which discards sibling keys.
- Calling
patchStatefrom a component instead of from a store method. Keep writes in methods so the store controls how its state changes.
Exercise
A store holds { cart: { items: string[]; coupon: string | null } }. Write the body of an addItem(item: string) method that keeps the coupon unchanged, and explain why patchState(store, { cart: { items: [item] } }) is wrong.
Show answer
Use patchState(store, (state) => ({ cart: { ...state.cart, items: [...state.cart.items, item] } }));. The shallow merge replaces the whole cart object, so the version in the question would discard the existing items and the coupon, and keep only the new item.