What is NGXS?
NGXS is a library for managing state in Angular, similar to NgRx, but with simpler syntax and less boilerplate.
If NgRx resembles Redux with RxJS, then NGXS is more like a class-based, "Angular-style" implementation of state management.
What NGXS does:
- Stores the application state in a Store
- just like in NgRx, all the state is centralized
- it can be read and updated
- Works through Actions
- actions describe what happened
- they trigger methods inside
Stateclasses
- Uses classes instead of reducers
- no need to write switch/case
- you just create methods with decorators
NGXS example:
ts
// actions
export class Increment {
static readonly type = '[Counter] Increment';
}
export class Decrement {
static readonly type = '[Counter] Decrement';
}ts
// state
@State<number>({
name: 'count',
defaults: 0
})
@Injectable()
export class CounterState {
@Action(Increment)
increment(ctx: StateContext<number>) {
const state = ctx.getState();
ctx.setState(state + 1);
}
@Action(Decrement)
decrement(ctx: StateContext<number>) {
const state = ctx.getState();
ctx.setState(state - 1);
}
}ts
// component
export class MyComponent {
count$ = this.store.select(state => state.count);
constructor(private store: Store) {}
plus() {
this.store.dispatch(new Increment());
}
}How it differs from NgRx:
| NGXS | NgRx | |
|---|---|---|
| Syntax | simpler, classes, decorators | stricter, function-based |
| Reducers | none, methods inside classes are used instead | yes, pure functions |
| Effects | called @Action() or @Effect() | createEffect() |
| RxJS | used, but less | used extensively |
Conclusion:
NGXS is a more "Angular-like" alternative to NgRx, with less code. It's a good fit if you want centralized state management without all of NgRx's heaviness.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.