State Management with Signals: A Simple Store Pattern
What Is State?
State is the data your app remembers: the logged-in user, cart items, selected filters, loaded lists. When state is shared between many components you need one clear place to keep it.
The Store Service Pattern
| Part | Role |
|---|---|
| Private writable signals | Only the store changes data |
| Public read-only signals | Components read data |
computed selectors | Derived values (totals, filtered lists) |
| Methods | Actions that change the state |
typescript
export interface CartItem { productId: number; name: string; price: number; qty: number; }
@Injectable({ providedIn: 'root' })
export class CartStore {
// state
private readonly _items = signal<CartItem[]>(this.load());
// read-only views
readonly items = this._items.asReadonly();
// selectors
readonly count = computed(() => this._items().reduce((n, i) => n + i.qty, 0));
readonly subtotal = computed(() => this._items().reduce((s, i) => s + i.price * i.qty, 0));
readonly isEmpty = computed(() => this._items().length === 0);
constructor() {
// persist automatically
effect(() => localStorage.setItem('cart', JSON.stringify(this._items())));
}
// actions
add(product: { id: number; name: string; price: number }) {
this._items.update(items => {
const found = items.find(i => i.productId === product.id);
return found
? items.map(i => i.productId === product.id ? { ...i, qty: i.qty + 1 } : i)
: [...items, { productId: product.id, name: product.name, price: product.price, qty: 1 }];
});
}
setQty(productId: number, qty: number) {
this._items.update(items =>
qty <= 0 ? items.filter(i => i.productId !== productId)
: items.map(i => i.productId === productId ? { ...i, qty } : i));
}
clear() { this._items.set([]); }
private load(): CartItem[] {
try { return JSON.parse(localStorage.getItem('cart') ?? '[]'); }
catch { return []; }
}
}
typescript
@Component({
selector: 'app-cart-badge',
template: `<a routerLink="/cart">Cart ({{ cart.count() }})</a>`,
imports: [RouterLink],
})
export class CartBadge { cart = inject(CartStore); }
Server-side rendering:
localStorage does not exist on the server. Check isPlatformBrowser or move storage code into afterNextRender when you use SSR.
Loading and Error State
typescript
export type LoadState = 'idle' | 'loading' | 'loaded' | 'error';
@Injectable({ providedIn: 'root' })
export class ProductStore {
private http = inject(HttpClient);
private _products = signal<Product[]>([]);
private _state = signal<LoadState>('idle');
readonly products = this._products.asReadonly();
readonly loading = computed(() => this._state() === 'loading');
readonly failed = computed(() => this._state() === 'error');
load() {
this._state.set('loading');
this.http.get<Product[]>('/api/products').subscribe({
next: list => { this._products.set(list); this._state.set('loaded'); },
error: () => this._state.set('error'),
});
}
}
When to Use NgRx
| App size | Suggestion |
|---|---|
| Small and medium | Signals in services (this lesson) |
| Large teams, many features, strict rules | NgRx (Store, Effects) or NgRx SignalStore |
| Need time travel debugging, strict action history | NgRx Store with DevTools |
typescript
// NgRx SignalStore example (package @ngrx/signals)
export const TodoStore = signalStore(
{ providedIn: 'root' },
withState({ todos: [] as Todo[], filter: 'all' }),
withComputed(({ todos, filter }) => ({
visible: computed(() => filter() === 'all' ? todos() : todos().filter(t => !t.done)),
})),
withMethods(store => ({
add(title: string) { patchState(store, s => ({ todos: [...s.todos, { id: Date.now(), title, done: false }] })); },
})),
);
Start simple: Most apps do not need a state library. A few well-designed store services with signals are easy to read, test and maintain.
Conclusion
Keep state in a store service with private signals, public read-only signals, computed selectors and methods as actions. Move to NgRx only when the app and team grow large.
Quick Summary: private signal + readonly view + computed + methods = simple store.

