Skip to content

State Management in Angular

“Which state management library should we use?” is almost always the wrong first question. The right one is where should each piece of state live, and for most state the answer is “closer than you think.”

Signals changed the calculus here. A great deal of what NgRx was adopted for — a predictable place for shared state, derived values that stay consistent, a testable unit — a signal-based service now does in twenty lines. That does not make stores obsolete; it moves the threshold at which one is worth its cost.

Work down this list and stop at the first level that fits.

Level Mechanism For
1. Component signal in the component Most state. UI-local, dies with the component
2. URL Route and query params Anything shareable, bookmarkable, or expected after a refresh
3. Feature service Signals in a service, Route.providers Shared within one feature and hidden from the rest; reset explicitly if it must not survive leaving
4. Root service Signals in a @Service() Genuinely application-wide
5. Store library NgRx or similar Large teams, complex flows, strict traceability

Most applications need levels 1–4 and nothing else. Skipping to level 5 by default is how a codebase acquires three files and forty lines of ceremony per boolean.

export class OrderEditor {
protected readonly isExpanded = signal(false);
protected readonly draft = signal<OrderDraft>({ lines: [] });
}

If no other component needs it and it should not survive navigation, it belongs here. Moving it “in case someone needs it later” is speculative coupling.

provideRouter(routes, withComponentInputBinding());
export class OrderList {
readonly status = input<string>('open');
readonly page = input(1, { transform: (v: string | undefined) => Number(v ?? 1) });
}

The URL is a free state container with properties no service gives you: shareable, bookmarkable, back-button-correct, restored on refresh. The test is whether a user would reasonably send someone this link and expect the same view. Filters, sorting, pagination, the selected tab, the open record — all yes.

Duplicating this state into a service is a common and costly mistake: two sources of truth that drift, and a back button that changes the URL without changing the screen. See Query Parameters.

@Service({ autoProvided: false })
export class OrdersFeatureState {
private readonly _selection = signal<ReadonlySet<string>>(new Set());
readonly selection = this._selection.asReadonly();
readonly selectionCount = computed(() => this._selection().size);
toggle(id: string): void {
this._selection.update((current) => {
const next = new Set(current);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
}
clear(): void {
this._selection.set(new Set());
}
}
{
path: 'orders',
providers: [OrdersFeatureState],
loadChildren: () => import('./orders.routes').then((m) => m.ordersRoutes),
}

Route.providers creates a child injector for the route subtree, so the service is shared by the feature’s screens and invisible to the rest of the application.

It does not reset on its own when the user leaves. By default Angular keeps the route’s injector — and so the service and its state — alive after navigation. If the state must be cleared on leaving, make that explicit:

@Component({ /* feature root component, e.g. OrdersShell */ })
export class OrdersShell {
constructor() {
const state = inject(OrdersFeatureState);
inject(DestroyRef).onDestroy(() => state.clear());
}
}

Alternatively, opt in to router-managed cleanup with withAutoCleanupInjectors() (Angular v22.2+), which destroys the injectors of routes that are no longer active or stored by the RouteReuseStrategy. The explicit reset is easier to reason about and test.

Reserve this for genuinely application-wide state: the authenticated user, the theme, feature flags, a notification queue. Root state lives for the whole session, which is why it should be a short list.

Whatever the level, the shape is the same and it is worth being disciplined about it.

@Service()
export class CartState {
// 1. Private writable state
private readonly _items = signal<readonly CartItem[]>([]);
private readonly _promoCode = signal<string | null>(null);
// 2. Public read-only signals
readonly items = this._items.asReadonly();
readonly promoCode = this._promoCode.asReadonly();
// 3. Derived values
readonly subtotal = computed(() =>
this._items().reduce((sum, i) => sum + i.price * i.quantity, 0),
);
readonly discount = computed(() => (this._promoCode() ? this.subtotal() * 0.1 : 0));
readonly total = computed(() => this.subtotal() - this.discount());
readonly isEmpty = computed(() => this._items().length === 0);
// 4. Methods as the only way to change state
add(item: CartItem): void {
this._items.update((items) => [...items, item]);
}
clear(): void {
this._items.set([]);
this._promoCode.set(null);
}
}

Four rules doing the work:

Private writable, public read-only. A public WritableSignal lets any component mutate shared state from anywhere, and you lose the ability to say what changes it. asReadonly() is the signal-era equivalent of exposing an Observable rather than a Subject.

One caveat: asReadonly() does not prevent deep mutation of the value. It blocks set and update; it does not freeze the object. Type values as readonly/Readonly<T> so the compiler helps.

Derive, never duplicate. total is a computed, not a field kept in sync. Every effect-maintained copy is eager work plus an invariant you maintain by hand.

Methods are the only mutations. They are where invariants live, where you can log, and what you name in a test.

Never mutate in place. Signals compare with Object.is; items().push(x) notifies nothing.

it('applies a promo discount to the total', () => {
const cart = TestBed.inject(CartState);
cart.add({ id: 'a', price: 100, quantity: 1 });
cart.applyPromo('SAVE10');
expect(cart.total()).toBe(90);
});

No fixture, no change detection, no marble diagram. This is the strongest practical argument for putting logic in signal-based state services rather than in components.

Loading, error and success states are a state-management problem, and resource solves it without any of the above:

readonly orders = httpResource<Order[]>(() => `/api/orders?status=${this.status()}`);

isLoading(), error(), value(), hasValue(), reload() — plus automatic cancellation of a superseded request when the params change. Hand-rolling this in a store is a large amount of code reproducing something the framework gives you, and getting the race conditions wrong on the way.

Use HttpClient directly for mutations, and re-fetch or update local state afterwards. See HttpClient and API Integration.

Real reasons, not aesthetic ones:

  • Many teams on one large application, needing an enforced convention more than the best convention.
  • Complex flows with real traceability requirements — an audit trail of what changed and why.
  • Time-travel debugging genuinely earning its keep.
  • Heavy cross-cutting side effects benefiting from an effects model.
  • An existing NgRx codebase. Migrating a working store to signals is rarely the highest-value work available.

Reasons that are not good enough: “it is what serious Angular applications use”, “we might need it later”, “one developer knows it well”.

NgRx Store — Redux for Angular: actions, reducers, selectors, effects. Maximum ceremony and maximum predictability. @ngrx/signals provides a much lighter signal-based store from the same project.

NgRx SignalStore — signal-native, far less boilerplate, keeps the structure. The natural choice if you want NgRx conventions without the Redux shape.

Other signal-based stores exist with similar goals; evaluate on maintenance activity and how much structure your team actually wants.

A plain signal service — the pattern above. Zero dependencies, no learning curve, and enough for most applications.

The decision is really about how much structure a team needs imposed. A small team gets consistency from convention and review; a large one may genuinely need it enforced by a library. That is an organisational judgement, not a technical one.

Two very different needs.

Restoring where the user was — belongs in the URL, not in storage. Then it works across devices, in a shared link, and with the back button.

Preserving preferences and drafts — localStorage or sessionStorage, written from an effect:

constructor() {
effect(() => localStorage.setItem('theme', this.theme()));
}

This is exactly what effects are for: syncing signal state into a non-signal, imperative API.

Three cautions. Validate what you read back — storage is user-editable and may hold data from an older version of your schema. Never store sensitive data: tokens, personal data, form contents from a payment or password screen. And storage is not state management — it is a cache of state that lives somewhere else.

Anti-pattern Cost
A global store for everything Ceremony per boolean; state that never dies
Public WritableSignal on a service Any component can mutate shared state
State duplicated between a service and the URL Two sources of truth; they drift
Derived values stored as fields Manual synchronisation; guaranteed to go stale
effect writing to another signal Extra CD cycles; ExpressionChangedAfterItHasBeenChecked; loops
Mutating a signal’s value in place No notification at all
Root scope for feature state Survives navigation; leaks between users in a tab
Hand-rolled loading/error state Reimplements resource, usually with a race condition
A store adopted before the problem exists Cost now, benefit maybe
Storage as the source of truth Stale, unvalidated, per-device

“Do you need NgRx?” Usually not, and increasingly less often. Signals give you a predictable place for shared state, consistent derived values, and a unit you can test without a fixture — which is most of what NgRx was adopted for. A store earns its cost when the constraint is organisational: many teams needing an enforced convention, or a domain with genuine traceability requirements. If a team already has a working NgRx codebase, migrating it is rarely the best use of their time, and @ngrx/signals is a lighter path if they want one.

“Walk me through deciding where a piece of state lives.” Four questions. Does anything outside this component need it? If not, it is a component signal. Would a user expect to share, bookmark, or refresh into it? If so, it goes in the URL — that is free and gives you the back button. Is it shared within one feature? A service provided by Route.providers — and if it must reset on leaving, reset it explicitly, because route injectors are not destroyed on navigation by default. Is it genuinely application-wide — the current user, the theme? A root service. The failure mode is putting everything at the last level, where state survives navigation, bleeds between users in a long-lived tab, and needs a reset method somebody forgets to call.

“What is wrong with a public WritableSignal on a service?” You lose the ability to say what changes the state. Any component can call set from anywhere, invariants have no single place to live, and the answer to “why is this value wrong?” becomes a search of the whole codebase. Expose asReadonly() and methods. And know the limit: asReadonly() blocks set and update but does not freeze the value, so deep mutation still works and notifies nobody — type it Readonly<T> so the compiler covers that gap.

“An effect keeps one signal in sync with another. Is that fine?” No, and it is the most common signal anti-pattern. It costs an extra change-detection cycle, risks ExpressionChangedAfterItHasBeenChecked, and can loop. If the value is derived, it is a computed. If it is derived and needs to be directly settable — a selection that resets when its source list changes — that is linkedSignal. Effects are for pushing state into things that are not signals: storage, logging, a canvas, a third-party widget.

“How do you handle loading and error states?” resource or httpResource, which give isLoading(), error(), value(), hasValue() and reload() as signals and cancel a superseded request automatically when the params change. Hand-rolling that in a store means reimplementing it and usually getting the race condition wrong — the slow response for the old params landing after the fast one for the new. Mutations stay on HttpClient, because a POST is a command with a moment of execution, not a value that re-derives.

“You inherit an application where every screen’s state is in root services. What breaks?” Data that should have gone away does not. A filter set on one screen is still applied when the user returns; a half-completed form persists across a logout; and in a long-lived tab where a second user signs in, the first user’s data is still in memory. The fixes are mechanical once you know the levels: feature-only state moves to Route.providers (with an explicit reset where it must not survive leaving), state a user would share moves to the URL, and state nothing else reads moves back into its component. That last move is usually the biggest, and the most satisfying.