{{announcement.body}}
{{announcement.title}}

State Management Using NGXS in Angular

DZone 's Guide to

State Management Using NGXS in Angular

A discussion of state management and how to implement it in an Angular app using NGXS.

· Web Dev Zone ·
Free Resource

Why Do We Need State Management?

When creating a web application, one of the questions to ask is how data should be managed. The next question is how this could this be performant and reliable. The current trend is to use a Redux-based storage solution, which consists of a Store, Selectors to get data from the store in the form of Observables, and Actions to modify the store. This allows for a single source of truth, a read-only state and the flow of data going in one direction.

Redux State Management Tool

Redux was built for React. Since it was designed for React, it lacked the necessary plumbing to make it work well with Angular. For state management in Angular, NGRX is used. NgRx Store provides reactive state management for Angular apps inspired by Redux.

NGXS

NGXS is also a state management pattern and library for Angular. As NGXS is modeled after the CQRS pattern popularly implemented in libraries with Redux, it reduces boilerplate by using modern TypesScript features such as classes and decorators.

There are four major concepts in NGXS:

  1. Store: The store is a global state manager that dispatches actions your state containers listen to and provides a way to select data slices out from the global state.
  2. Actions: Actions describe unique events that are dispatched from components and services. Each action contains a type field which is their unique identifier and payload required for that action.
  3. State: Class definition of the state. State changes are handled by pure functions also called reducers that take the current state and the latest action to compute a new state.
  4. Selects: Selectors are pure functions used to select, derive and compose pieces of state.

These concepts create a circular control flow traveling from a component dispatching an action, to a store reacting to the action, back to the component through a state select.

NGXS architecture

NGXS Example

Actions

Actions can either be thought of as a command which should trigger something to happen, or as the resulting event of something that has already happened. Each action contains a type field which is their unique identifier and payload for that action.

export interface ZebraFood {
  name: string;
  hay: number;
  carrots: number;
}
export class FeedZebra { 
    static readonly type = '[Zoo] Feed Zebra';  
    constructor(public zebraToFeed: ZebraFood) {}
}

In this action, zebra is feed with FeedZebra. This type of the action is triggered to feed the zebra with hay. The  zebraToFeed field of the action class will represent the amount of food for the zebra we should feed.

State

States are classes along with decorators to describe metadata and action mappings. A state definition is:

@State<string[]>({
  name: 'animals',
  defaults: {
    zebraFood: []
  }
})

In the state decorator, we have metadata for the state. The name property is used to state the name of state to slice. Name is a required parameter and must be the unique for the application. defaults is a set of objects/arrays for this state slice.

Actions can also pass along metadata that has to do with the action. We can use the following code to pass along how much hay and carrots a zebra needs.

@Action(FeedZebra)
  feedZebra(ctx: StateContext<ZooStateModel>, action: FeedZebra) {
    const state = ctx.getState();
    ctx.setState({
      ...state,
      zebraFood: [
        ...state.zebraFood,
        // this is the new ZebraFood instance that we add to the state
        action.zebraToFeed,
      ]
    });
  }

Select

Selects are functions that slice a specific portion of state from the global state container. Slices of data from the store are selected by using the @Select decorator.

@Select(state => state.zoo.animals) animals$: Observable<string[]>;

The store class has a select function:

export class ZooComponent {
  animals$: Observable<string[]>;

  constructor(private store: Store) {
    this.animals$ = this.store.select(state => state.zoo.animals);
  }
}

NGXS vs. NGRX

NGXS ang NGRX are both state management libraries for Angular applications. Both of them share the redux principle. It depends on your preferenece as to which one to choose, as NGXS is more angularish because it uses modern TypeScript features.

Visit the NGXS docs for further documentation.

Topics:
web dev ,angular ,ngxs tutorial ,state management

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}