Redux with Angular & ngrx

Web apps become increasingly complicated

Everything is connected to everything

Ever-changing state

Changing something
breaks
something somewhere

Solution ?

Redux

Predictable state container for JavaScript apps

Inspired by / Based on

Flux architecture

(unidirectional data flow)

CQRS

(Command Query Responsibility Segregation)

Event sourcing
(
application state changes as a sequence of events)

Immutables

Concepts

3 fundamentals principles

Single source of truth

The state of your whole application is stored in an object tree within a single store

{
  todos: [
    {
      text: 'Consider using Redux',
      completed: true,
    },
    {
      text: 'Keep all state in a single tree',
      completed: false
    }
  ],
  filter: 'SHOW_ALL'
}

State is read-only

The only way to change the state is to emit an action, an object describing what happened

{
  type: 'ADD_TODO',
  text: 'Visit delair.aero'
}
{
  type: 'SET_VISIBILITY_FILTER',
  filter: 'SHOW_COMPLETED'
}

Changes as pure functions

To specify how the state tree is transformed by actions, you write pure functions (reducers)

function todos(state = {}, action) {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        ...state,
        todos: [
          ...state.todos,
          {
            text: action.text,
            completed: false
          }
        ]
      }
    case 'SET_VISIBILITY_FILTER':
      return {
        ...state,
        visibilityFilter: action.filter
      }
    //...
  }
}

Easier to reason about

Easier to debug or inspect

Benefits

Dev tools (time travel & HMR)

Easier to test

ngrx

Implementation of Redux on top of Angular & RxJS

Demo

@ngrx/store

RxJS powered state management for Angular applications, inspired by Redux

Selectors

Selectors can compute derived data, to store minimal possible state

Selectors are efficient (pure function). A selector is not recomputed unless one of its arguments change (memoization)

Selectors are composable. They can be used as input to other selectors

Demo

@ngrx/effects

Side Effect model for @ngrx/store to model event sources as actions

Demo

@ngrx/entity

Entity State adapter for managing record collections

State Normalization

Each type of data gets its own "table" in the state

Each "data table" should store the individual items in an object

Any references to individual items should be done by storing the item's ID.

Arrays of IDs should be used to indicate ordering.

Demo

@ngrx/router-store

Bindings to connect the Angular Router to @ngrx/store

Conclusion

You might not need Redux

You’ll know when you need Redux

Long learning curve

Great development experience

Fits well with Angular

Ressources

Questions ?

Redux with Angular & ngrx

By Bruno Baia

Redux with Angular & ngrx

  • 1,059