NashTech Insights

Introduction to NGXS: State Management Made Easy

Alka Vats
Alka Vats
Table of Contents


In modern web development, managing the application state is crucial to building robust and scalable applications. Traditional approaches like using local component states can become complex and hard to maintain as your application grows. This is where state management libraries like NGXS come to the rescue. NGXS is a powerful state management library for Angular applications that helps you centralize and organize your application state. In this blog, we’ll explore the key concepts of NGXS and provide a hands-on example to showcase its benefits.

If you want to learn about the NGRX, state management angular, you can refer here.

Understanding NGXS:

NGXS is inspired by Redux and centralizes the application state. It follows the unidirectional data flow pattern, making state changes predictable and traceable. NGXS promotes the use of immutable data and encourages developers to write pure functions to update the state, ensuring that the state remains immutable and changes are tracked efficiently.

Key Concepts of NGXS:

  1. State: The state represents the data that drives your application. It is stored in a centralized store and should be treated as immutable.
  2. Actions: Actions are plain JavaScript objects that describe an intention to change the state.
  3. Mutations: Mutations are responsible for updating the state based on the dispatched actions. They are pure functions that receive the current state and the action payload and return a new state.
  4. Store: The store is the central repository that holds the state of your application. It dispatches actions, applies mutations, and notifies subscribers about state changes.
  5. Selectors: Selectors are used to retrieve specific portions of the state from the store. They are pure functions that transform the raw state into a desired format for consumption.

Hands-On Example:

Let’s create a simple NGXS application to manage a list of tasks. Here are the steps:

1. Set up a new Angular project:
ng new ngxs-example
2. Install NGXS dependencies:
npm install @ngxs/store @ngxs/logger-plugin
3. Create a Task model:
// task.model.ts
export interface Task {
  id: number;
  title: string;
  completed: boolean;
4. Create a state class:
// task.state.ts
import { State, Action, StateContext } from '@ngxs/store';
import { AddTask, ToggleTask } from './task.actions';
import { Task } from './task.model';

  name: 'tasks',
  defaults: []
export class TaskState {
  addTask({ getState, setState }: StateContext<Task[]>, { payload }: AddTask) {
    const state = getState();
    const newTask: Task = {
      id: Math.random(),
      title: payload,
      completed: false
    setState([...state, newTask]);
  toggleTask({ getState, patchState }: StateContext<Task[]>, { payload }: ToggleTask) {
    const state = getState();
    const taskIndex = state.findIndex(task => === payload);
    const updatedTasks = [...state];
    updatedTasks[taskIndex].completed = !updatedTasks[taskIndex].completed;
5. Create actions:
// task.actions.ts
export class AddTask {
  static readonly type = '[Tasks] Add';
  constructor(public payload: string) {}

export class ToggleTask {
  static readonly type = '[Tasks] Toggle';
  constructor(public payload: number) {}
6. Register the NGXS module and plugins:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxsModule } from '@ngxs/store';
import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin';
import { AppComponent } from './app.component';
import { TaskState } from './task.state';

  declarations: [AppComponent],
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule {}
7. Use the state in a component:
// app.component.ts
import { Component } from '@angular/core';
import { Store } from '@ngxs/store';
import { AddTask, ToggleTask } from './task.actions';
import { Task } from './task.model';

  selector: 'app-root',
  template: `
      <input [(ngModel)]="taskInput" placeholder="Enter task" />
      <button (click)="addTask()">Add Task</button>
        <li *ngFor="let task of tasks$ | async" [class.completed]="task.completed">
          <span>{{ task.title }}</span>
          <button (click)="toggleTask(">Toggle</button>
  styles: [
    .completed {
      text-decoration: line-through;
export class AppComponent {
  tasks$ = => state.tasks);
  taskInput = '';

  constructor(private store: Store) {}

  addTask() { AddTask(this.taskInput));
    this.taskInput = '';

  toggleTask(taskId: number) { ToggleTask(taskId));


NGXS provides a powerful and intuitive way to manage application states in Angular projects. By following the principles of unidirectional data flow and immutability, NGXS helps you build scalable and maintainable applications. In this blog, we covered the key concepts of NGXS and demonstrated a practical example of how to use NGXS for state management. Now you’re ready to leverage NGXS to efficiently handle state in your Angular applications. Happy coding!

Finally, for more such posts, please follow our LinkedIn page- FrontEnd Competency.

Alka Vats

Alka Vats

Alka Vats is a Software Consultant at Nashtech. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: