What is @ngxs/store?
@ngxs/store is a state management library for Angular applications, inspired by the Redux pattern. It provides a simple and intuitive API for managing application state, making it easier to develop, test, and maintain Angular applications.
What are @ngxs/store's main functionalities?
State Management
This code demonstrates how to define a state and an action in @ngxs/store. The `TodoState` class manages a list of todos, and the `AddTodo` action allows adding a new todo to the state.
import { State, Action, StateContext } from '@ngxs/store';
export class AddTodo {
static readonly type = '[Todo] Add';
constructor(public payload: string) {}
}
export interface TodoStateModel {
todos: string[];
}
@State<TodoStateModel>({
name: 'todos',
defaults: {
todos: []
}
})
export class TodoState {
@Action(AddTodo)
add(ctx: StateContext<TodoStateModel>, action: AddTodo) {
const state = ctx.getState();
ctx.setState({
...state,
todos: [...state.todos, action.payload]
});
}
}
Selectors
Selectors in @ngxs/store are used to query specific pieces of state. This example shows how to create a selector to get the list of todos from the state.
import { Selector } from '@ngxs/store';
import { TodoStateModel } from './todo.state';
export class TodoSelectors {
@Selector([TodoStateModel])
static getTodos(state: TodoStateModel) {
return state.todos;
}
}
State Context
The StateContext provides methods to interact with the state, such as `getState` and `setState`. This example shows how to use the StateContext to update the state when an action is dispatched.
import { StateContext } from '@ngxs/store';
export class TodoState {
@Action(AddTodo)
add(ctx: StateContext<TodoStateModel>, action: AddTodo) {
const state = ctx.getState();
ctx.setState({
...state,
todos: [...state.todos, action.payload]
});
}
}
Other packages similar to @ngxs/store
akita
Akita is a state management library for Angular applications that focuses on simplicity and performance. It provides a straightforward API for managing state and includes features like entity management and store queries.
mobx-angular
MobX is a state management library that uses reactive programming principles. MobX-Angular is an integration of MobX with Angular, providing a different approach to state management compared to @ngxs/store, focusing on observables and reactions.