What is state management in angular? and why should I use it?

First, to answer your question, you should know that State Management is not a term of Angular, and you don’t have to use it. State Management is a term that defines a way we can store data, modify it, and react to its changes. In our case, the libraries NGRX and NGXS are using a pattern called CQRS (Command Query Responsibility Segregation) principle, and I quote Wikipedia:

It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both.

State Management acts as a single source of truth for your application.

You can build an app without complex State Management. You can use only services, and you’re good to go. Adding a State Management library (e.g NGRX/NGXS) to your application would add some complexity and boilerplate, but then you’ll have the benefits of (quoted from https://stackoverflow.com/a/8820998/1860540):

  1. Large team – You can split development tasks between people easily if you have chosen CQRS architecture. Your top people can work on domain logic leaving regular stuff to less skilled developers.
    2. Difficult business logic – CQRS forces you to avoid mixing domain logic and infrastructural operations.
    3. Scalability matters – With CQRS you can achieve great read and write performance, command handling can be scaled out on multiple nodes and as queries are read-only operations they can be optimized to do fast read operations.

The most popular Angular’s State Management libraries are NGRX and NGXS.

I won’t elaborate on NGRX, but in short – it has proven itself in real production applications.

However, NGXS is a younger state management library for angular that adopted some ideas of NGRX and “empowered” it by using the tools that Angular provides (such as DI). The main difference between NGRX and NGXS is that your boilerplate is significantly less on NGXS. If you’re interested, you can read the main reason Why another state management for Angular.

So to sum it up – If you’re planning on building a large scaled application, then you should consider using State Management, although – you don’t have to.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)