Sub topic 3
Defining state with withState
This chapter assumes you can write Angular components and inject services. It also assumes you know signal and computed, and can read TypeScript object types and generics. You have already seen signalStore create a store. Here you will look closely at the feature that gives a store its state: withState.
What withState does
withState is a store feature that declares the initial state of a store. You pass it an object. The store then exposes each top-level property of that object as a read-only signal.
import { signalStore, 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),
);An instance of TodosStore now has two members: todos is a Signal<Todo[]> and filter is a Signal<Filter>. You read them by calling them, as with any signal: store.todos() and store.filter().
One signal per top-level property
The store does not hand you one big signal holding the whole object. It creates one signal for each top-level key. This has a practical effect on change detection and computed values.
Suppose a computed signal reads only store.filter(). When todos changes, that computed value does not recompute, because it never depended on todos. If the state were a single signal, every change would invalidate every reader.
You can still get the whole state as a plain object when you need it, for example for logging or persistence. Use getState:
import { getState } from '@ngrx/signals';
const snapshot = getState(store);
console.log(snapshot.filter);getState returns the current state as a plain object. It is not a signal, so calling it inside a computed or effect is a way to read all keys at once and track them.
Reading state in a component
Because state keys are signals, a template reads them with call syntax. No async pipe and no subscription is needed.
import { Component, inject } from '@angular/core';
import { TodosStore } from './todos.store';
@Component({
selector: 'app-todo-filter',
template: `
<p>Current filter: {{ store.filter() }}</p>
<p>{{ store.todos().length }} todos loaded</p>
`,
})
export class TodoFilterComponent {
readonly store = inject(TodosStore);
}The component never assigns to store.filter. State keys are Signal, not WritableSignal, so there is no set or update method on them. Writing happens through patchState, which a later chapter covers.
Typing the state
TypeScript infers the state type from the object you pass. That works well when every value has a precise literal type, but it goes wrong in three common cases.
Empty arrays
{ todos: [] } is inferred as never[], and you could not add anything to it later. Annotate the state, either with a typed constant as shown above or with the generic parameter:
import { signalStore, withState } from '@ngrx/signals';
type User = { id: number; name: string };
export const UsersStore = signalStore(
withState<{ users: User[] }>({ users: [] }),
);Unions and literals
{ filter: 'all' } is inferred as { filter: string }. The Filter annotation keeps the type as 'all' | 'open' | 'done', so consumers get exhaustive checking in switch statements.
Values that start empty
A value that is not available at startup, such as the signed-in user, needs null in its type:
import { signalStore, withState } from '@ngrx/signals';
type User = { id: number; name: string };
type SessionState = {
user: User | null;
error: string | null;
loading: boolean;
};
export const SessionStore = signalStore(
withState<SessionState>({ user: null, error: null, loading: false }),
);Prefer null over optional properties such as user?: User. The store builds its signals from the keys present in the initial object. A key that is missing at startup gets no signal, and adding it later does not create one. Declaring every key up front, with null for "no value yet", keeps the set of signals fixed.
Rules for the state shape
The root of the state must be a plain object. Arrays, Map, Set, Date and primitives are not valid as the root. They are fine as values of a key:
| Root state | Valid | Reason |
|---|---|---|
| `{ items: [] }` | Yes | A plain object, with the array as a value |
| `[]` | No | The root must be an object with keys |
| `42` | No | A primitive has no keys to become signals |
| `{ createdAt: new Date() }` | Yes, with care | The `Date` is a value, but it is not a plain object |
State should be serializable data: strings, numbers, booleans, arrays and plain objects. Keeping class instances, functions and Map objects out of state makes it easy to log, persist and compare in tests. It also fits the immutable updates you will use with patchState.
Initial state as a factory
withState accepts either an object or a function that returns one. The function form runs once for each store instance.
import { inject } from '@angular/core';
import { signalStore, withState } from '@ngrx/signals';
import { Settings } from './settings.service';
type PrefsState = { theme: 'light' | 'dark'; pageSize: number };
export const PrefsStore = signalStore(
withState(() => {
const settings = inject(Settings);
return { theme: settings.defaultTheme, pageSize: settings.defaultPageSize } satisfies PrefsState;
}),
);The factory runs in an injection context, so inject works inside it. Use the factory form in two situations:
- The initial value depends on a service, such as saved settings or a route parameter.
- The store is provided at component level, so each component gets its own instance, and the initial state contains arrays or nested objects. With a shared constant object, every instance starts from the same references. Patching replaces objects instead of mutating them, so this is usually harmless. A factory removes any doubt.
The Settings service above is an example name. Replace it with a service from your own project.
Combining several withState calls
You can call withState more than once in one store. The features run in order and their state keys are merged.
import { signalStore, withState } from '@ngrx/signals';
export const DashboardStore = signalStore(
withState({ title: 'Overview' }),
withState({ widgets: [] as string[], refreshSeconds: 30 }),
);DashboardStore has three signals: title, widgets and refreshSeconds. Splitting state this way is useful when a custom feature contributes its own slice. A later chapter shows signalStoreFeature doing exactly that.
Nested state and deep signals
State can contain nested objects. The store gives you a signal for the top-level key, and it also makes the nested properties available as signals of their own. These are called deep signals.
import { signalStore, withState } from '@ngrx/signals';
export const SettingsStore = signalStore(
withState({
user: { firstName: 'Ada', lastName: 'Lovelace' },
ui: { sidebarOpen: true },
}),
);
// store.user() -> { firstName: 'Ada', lastName: 'Lovelace' }
// store.user.firstName() -> 'Ada'A later chapter covers deep signals in detail. For now, remember that only the first level creates signals through withState itself, and deeper levels are derived views of the same data.
Design guidelines for state
- Store the minimum. If a value can be calculated from other state, calculate it with
withComputedinstead of storing it. A storedopenCountcan fall out of sync withtodos, but a computed one cannot. - Keep state flat where you can. Flat keys such as
loading,errorandqueryare easier to patch than deeply nested objects. - Model loading explicitly. A
loading: booleanand anerror: string | nullpair is the common minimum for a store that calls an API. - Give every key a real initial value. Empty array, empty string,
falseornullall work.undefineddoes not.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Type error when adding to an array | Inferred as `never[]` | Annotate the state type |
| `store.something` is missing at runtime | The key was absent from the initial state | Add it with an initial value, using `null` if needed |
| Type error on `store.filter.set(...)` | State signals are read-only | Update with `patchState` inside a store method |
| Type error on `patchState` in a component | State is protected | Add a method with `withMethods` |
| Two stores share unexpected values | Mutating a shared initial object | Replace objects when you update, or use the factory form |
Exercise
A store is defined with withState({ items: [], selectedId: undefined }). Name two problems with this initial state and write a corrected version.
Show answer
First, items: [] is inferred as never[], so the array can never hold typed items. Second, selectedId: undefined does not give the store a reliable signal to track, and the type is just undefined. A corrected version annotates the state and uses null: type Item = { id: number; name: string }; type State = { items: Item[]; selectedId: number | null }; withState<State>({ items: [], selectedId: null }).
Exercise
When would you pass a function to withState instead of an object?
Show answer
Use the function form when the initial state depends on something from the injection context, such as a service called through inject, or when each store instance should build its own fresh initial objects. The function runs once per store instance.