DEV Community

Cover image for Ngrx - Core Principles & New Features
Ilyoskhuja
Ilyoskhuja

Posted on

Ngrx - Core Principles & New Features

Ngrx is a powerful and popular library for building reactive applications in Angular. It provides a complete set of tools for managing state and side effects in your application. In this article, we'll cover the core principles of Ngrx and explore some of its new features.

Core Principles

Immutable State: Ngrx stores state as an immutable data structure, which means that state cannot be changed directly. Instead, state changes must be performed through actions and reducers.
Unidirectional Data Flow: Ngrx follows the unidirectional data flow pattern, where data flows in a single direction from actions to reducers to state.
Separation of Concerns: Ngrx separates state management from business logic, making it easier to maintain and test your application.

New Features

Facades: Ngrx 8 introduces facades, which provide a simple and intuitive way to access and manipulate state from components. Facades are generated automatically for you, and you can use them just like any other service in Angular.
Example:

@Injectable()
export class ProductsFacade {
  products$ = this.store.pipe(select(selectAllProducts));

  constructor(private store: Store<AppState>) {}

  addProduct(product: Product) {
    this.store.dispatch(addProduct({ product }));
  }
}
Enter fullscreen mode Exit fullscreen mode

Actions: Ngrx 8 also introduces a new and improved way to create actions, using the createAction function. This makes it easier to define and manage your actions, and also provides better type checking for your action payloads.
Example:


export const addProduct = createAction(
  '[Products] Add Product',
  props<{ product: Product }>()
);

Enter fullscreen mode Exit fullscreen mode

Selectors: Ngrx 8 provides improved support for selectors, making it easier to select and manipulate state in your application. Selectors can now be created as simple functions, and you can also use memoization to optimize performance.
Example:

export const selectAllProducts = createSelector(
  selectProductsState,
  (state: ProductsState) => state.products
);

Enter fullscreen mode Exit fullscreen mode

In conclusion, Ngrx provides a powerful and flexible toolset for building reactive applications in Angular. With its core principles of immutability, unidirectional data flow, and separation of concerns, and its new features like facades, actions, and selectors, Ngrx makes it easier to build and maintain complex applications.

Top comments (0)