The complexity of an application grows multi-fold if it consists of a large number of modules. With the growing number of modules, you also have to ensure that there is proper maintenance of the state machine. It would be catastrophic if module ‘A’ uses state ‘A’ and module ‘B’ uses state ‘B’.

Central state management becomes extremely essential when the application becomes bigger, and the state has to be shared between multiple modules. It is one of the hardest problems when it comes to building front-end applications. This is where Redux, an open-source JavaScript library for managing application state can be useful.

In this blog, we have a look at Redux, NgRx, and state management for enterprise applications using Redux & NgRx. Below are the sub-topics covered as a part of this blog

  • Introduction to Redux
    • Building blocks of Redux
    • Advantages of Redux
    • Necessity of using Redux in enterprise applications
  • Introduction to NgRx
    • Benefits of using NgRx
  • Example – State Management for Enterprise Angular Applications

What is Redux

In simple words, Redux is a state management tool primarily used for JavaScript applications. With Redux, developers can write applications with consistent behaviour across different environments like native, client, and server.

It can be used with any modern JavaScript (JS) based web framework, provided there is a binding of Redux with the framework e.g. ng-redux, reach-redux, etc.. However, it is often used with Angular or React for building user interfaces. The latest stable version of Redux is 4.0.4. The home-page of Redux is https://redux.js.org/

Building blocks of Redux

Before we deep dive into how Redux can be used to make Asynchronous (Async) calls to an external API, we have a look at the core building blocks of Redux.

ASync Development – Using Angular and Redux

In Redux, the state is managed by the store. The state is not mutated, which ensures that the state being used is never stale.

State/Store are single data structures used in the application. State and Store are the key components of the Redux architecture. Applications or components read the state from the store, i.e. the state is never mutated directly. Actions are passed to the Reducer function, which creates a new application state. The state contains the updates that Actions is making to the data.

Advantages of Redux

There are several benefits of using Redux; the major advantages are listed below:

  • Centralized state machine makes it easier to have persistent data between page refreshes, logging on data changes, etc.
  • Testing becomes easier due to the usage of pure reducer functions, along with other useful features like travel-time debugging.
  • A better understanding of data flows between applications due to predictable state updates.

Is Redux necessary for Angular?

There is a common confusion ‘Whether Redux is a must for building Angular applications?’ Redux is not necessary to be used in Angular applications.

However, it is highly recommended to use it in mid-scale & large-scale applications, as a central store that keeps track of the system state, providing a significant impact on system debugging and testing.

Without any type of Flux implementation, synchronization of data and events within the moving parts of an interactive application can turn out to be a painful experience. It becomes extremely difficult to manage especially for large-scale applications.

Later in the blog, we would be discussing how we used Redux and NgRx for state management for a US-based utility customer.

What is NgRx

NgRx is an Angular version of the Redux pattern.

NgRx provides the following:

  • Isolation of side effects
  • State Management
  • Entity Management
  • Router Bindings
  • Code Generation
  • Developer tools to provide improved developer experience

The primary purpose of NgRx is to provide a predictable state container to create maintainable explicit applications.

Benefits of using NgRx

The primary benefits of using Redux/NgRx architecture are below:

  • Consistent behaviour of applications as the state-handling is not split between multiple services.
  • Debugging and testing become a lot easier as Pure functions within the reducers are used to handle changes in the state.
  • Understanding the flow of data in the applications becomes much easier & predictable as you get well-versed with NgRx.

Shown below is the flow of application state in NgRx

NGRX State Management Lifecycle

State Management for Enterprise Angular Applications

To demonstrate the usage of NgRx/Redux, we take the example of a technical challenge that we encountered when implementing state management in the application for a US-based smart utility customer.

The end-customers of the smart-metering portal could access the information from different mediums, i.e. official website, web app, etc. As the application consisted of a large number of pages, the data on all the pages were required to be consistent.

We made extensive use of Redux and NgRx for state management, thereby ensuring that it provides consistent information on different components within the application.

Shown below is the code snippet of the key players, i.e. Actions, Effects, and Dispatchers that constitute the Store:

Actions

Actions in NgRx constitute of two main properties – type and payload. Type is a string property that indicates what kind of action needs to be performed. Payload is the additional information is required to be sent along with the type to process the action.

Shown below is the declaration of AccountDetailsRequest() where the action type is MyAccountActionType.AccountDetailsRequest. As discussed earlier, the action type is read-only

export class AccountDetailsRequest implements Action {

    readonly type = MyAccountActionType.AccountDetailsRequest;

    constructor(public payload: AccountDetailsTO) { }

}

*This is how to dispatch the above action from a component

this.store$.dispatch(new MyAccountActions.AccountDetailsRequest(accDetails));

Effects

NgRx effects enable to listen to action types and perform operations when the action happens. Any effect in NgRx is Observable i.e. action stream is used as the source as well as the destination.

In the code snippet shown below, we are making http REST call getAccountDetails.

@Effect()

accountDetails$: Observable<Action> = this.actions$.pipe(

        ofType(MyAccountActionType.AccountDetailsRequest),

        switchMap((action: AccountDetailsRequest) => this.accountService.getAccountDetails(action.payload)),

        map(accountDetails => new AccountDetailsSuccess(accountDetails))

    );

Reducers

Reducers in NgRx are pure functions that are responsible for handling each state transition synchronously. Inputs to a Reducer function are latest actions that are dispatched and the current state maintained in the Store.

It determines whether the modified state or original state has to be returned. In the code snippet shown below, the Reducer function myAccountReducers() returns the new state of accountDetails object to the Store.

export function myAccountReducers(state: MyAccountState = initialMyAccountState, action: MyAccountActionUnion) {

    switch (action.type) { 

        case MyAccountActionType.AccountDetailsSuccess:

            return { state, accountDetails: action.payload };

    

        default:

            return state;

    }

}

Conclusion

In this blog, we had an in-depth look at Redux, NgRx, and how to implement state management with Redux and NgRx. State management can get messy if not maintained properly and a flux application (like Redux) is ideal in such scenarios.

Learn more on Async Development using Redux and Angular with Tekgeminus. Our expertise across a wide spectrum of technologies helps simplify the complexities of their implementation, scripting client’s success.

Spread the love

Leave a Reply

Book a demo

Get to know how we work


     

    This will close in 0 seconds