Angular Signals bring fine-grained reactivity to Angular apps. But did you know you can also use them as a state management solution?
What Are Signals in Angular?
Signals are reactive primitives introduced in Angular to track and respond to changes in state. Unlike traditional @Input() and RxJS observables, Signals provide a simpler and more predictable API for state reactivity.
import { signal } from '@angular/core';
const count = signal(0);
console.log(count()); // o/p 0
count.set(1);
console.log(count()); // o/p 1
Using Signals as a Store
You can use signal(), computed(), and effect() together to create a reactive store.
Example: Counter Store
// counter.store.ts
import { signal, computed } from '@angular/core';
const _count = signal(0);
export const count = computed(() => _count());
export const increment = () => _count.update((val) => val + 1);
export const decrement = () => _count.update((val) => val - 1);
Using in Component
@Component({
selector: 'app-counter',
standalone: true,
imports: [CommonModule],
template: `
<h2>Count: {{ count() }}</h2>
<button (click)="increment()">+</button>
<button (click)="decrement()">-</button>
`,
})
export class CounterComponent {
count = count;
increment = increment;
decrement = decrement;
}
๐ฏ Benefits of Using Signals as a Store
**
- ๐ง Simple API compared to Redux or NgRx
- ๐ Lightweight and requires no external libraries
- ๐งฉ Fits well in component-driven architecture
- ๐ Built-in reactivity without RxJS boilerplate
โ ๏ธ When NOT to Use Signals as a Store
- โ Complex state flows or entity management
- โ Need for time-travel debugging
- โ Cross-module communication in large apps
For such use cases, libraries like NgRx or Akita might be more appropriate.
*โ
Best Practices
*
- Group signals by feature/domain
- Use computed() to avoid unnecessary recomputation
- Use effect() for side effects like API calls or logging
- Avoid overusing global signals โ isolate state where possible
๐ Conclusion
Angular Signals offer a lightweight and efficient way to manage local or feature-level state._ For apps that don't need the complexity of NgRx, Signals can keep your code reactive, clean, and maintainable.
_
Stay tuned for a deeper dive into effect() and how to handle side effects in your Signal-powered Angular apps!
Top comments (0)