Introduction to NgRx – NgRx Basics

579
SHARES
2.6k
VIEWS

Today, we will learn NgRx and how to manage state in our angular applications. NgRx is one of the most popular Rxjs based library used for managing state in angular applications. It is a Redux implementation for Angular, a popular and predictable state management library for JavaScript apps.

What is NgRx?

Ngrx is a group of Angular libraries for reactive extensions. Ngrx implements the same Redux pattern using the well-known RxJS observables of Angular 2+. Ngrx provides several benefits by simplifying your application state to plain objects, enforcing unidirectional data flow.

NgRx Features:

  • ngrx aims to bring reactive extensions to Angular.
  • @ngrx/store brings a Redux-like single store for all of your app states to Angular.
  • ngrx shares the same principles with redux and supercharging it with RxJS.

What Is Reactive Programming?

Reactive programming is a way to handle events and data flow in applications. In reactive programming, you design your components and other pieces of your software in order to react to those changes instead of asking for changes. A great tool for reactive programming, as you might know, is RxJS.

What is RxJS?

RxJS is a JavaScript library for reactive programming that allows you to work with asynchronous data streams. A stream is a sequence of values in time. This streams of events and data in real-time – which we call Observables – a beautiful way to handle asynchronous code. RxJS offers numerous ways to create streams. Whatever situation you are facing, there is one perfect way for you to create a stream. You may not need them all, but knowing them can save you time and some code.

Using RxJS, we would write something like this:

var button = document.querySelector('button');

Rx.Observable.fromEvent(button, 'click')
    .subscribe(() => console.log('Button Clicked!!!'));

var arr = Rx.Observable.of(60, 70)
    .subscribe((v) => console.log('Value:', v));

As we can see, by using RxJs we can achieve so much with very little amount of code.

What is Redux?

Redux, as stated earlier above, is a state management library for JavaScript applications. Redux implements the ideas of Flux. Flux is a design pattern that made popular one-way data flow (unidirectional flow), which was first introduced by Facebook. Redux was initially developed for the React.js community, But it can also be used with vanilla JavaScript or any other JavaScript framework.

States of an app in Redux are kept in the store. The states are updated using actions transported to pure functions called reducers. Reducers take in state and action as parameters and performs an immutable action on the state and returns a new state.

Before we dive further, let’s take a look at the core concepts of NgRx. NgRx Applications must deal with the StoreState, Reducers, and Actions.

What is a Store in ngrx?

In simple words, Store is what holds the app’s state. It comprises of different states defined in our application. The state, thus, is immutable and only altered by actions.

The store combines the whole application state into a single entity, acting as a database for the web application. Like a traditional database it represents the point of record for an application, your store can be thought of as a client side “single source of truth”.

What is a Reducer in ngrx?

Reducers are pure functions that are the only ones that can change state.  Reducers isn’t really changing state, it makes a copy of existing state and then change the properties on the new state.

export function reducer(state = initialState, action: post.Actions):State {
    switch(action.type) {
        case 'ADD_POST':
            return { 
                posts: [...state.posts,action.payload]
            }
        default:
            return state;
    }
}

What is State in NgRx?

State is a single immutable data structure. States are what makes up the store. As stated before, the reducers are like tables, and thus state are fields in the table.

What is Action in NgRx?

Store encompasses the state of our application and reducers get the state slices or sections of the store, but how do we update the store when the need arises? That is the role of the actions. Actions represent payloads of information that are dispatched to the store from the application and are usually triggered by user interaction.

// That's the Action interface
export interface Action {
    type: string,
    payload?: any
}

// Action with payload
dispatch({type: 'ADD_POST', payload: {link: 'github.com/philipszdavido', points:90}})

// Action without payload
dispatch({type:'LOAD_LINKS'})

When an action is dispatched, the reducer takes it and applies the payload, depending on the action type, and outputs the new state.

To recap a few points: The store encompasses the whole state, the reducers return fragments of the state, and actions are predefined user-triggered events that communicate how a given frame of the state should change.

Benefits of the Store

We have seen how effective and useful @ngrx/store is for managing states in our app. Now we’ll take a look at its advantages.

  • Testing: It is easy to write tests for pure functions. Since the store is composed of reducers – which are pure functions that use only its inputs to produce its outputs with no side effects. Simply input in, and assert the output.
  • Centralized State: State in a store is kept in one directory. It makes it easier to foretell updates or changes to the store, and track down problems
  • Performance: Unidirectional data-flow state changes from its reactivity makes it very fast and efficient.
  • DevTools: Awesome tools have been created to help developers like ngrx/store-devtool, which helps developers time travel during development. It also has some nice features that helps provide a history of actions and state changes.

What is a Selector?

Selector is a function used for obtaining a part of the state from the store.

What is a Effect in ngrx?

A method that listens for dispatched actions in an observable stream, processes the server response, and returns new actions either immediately or asynchronously to the reducer to change the state.

Conclusion

In this tutorial, we’ve learned the basic concepts of Ngrx. I’ll be posting a more detailed ngrx tutorial with examples very soon.

Leave a Reply

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

Trending