Convert Figma logo to code with AI

ngrx logoplatform

Reactive State for Angular

8,001
1,966
8,001
63

Top Related Projects

95,657

Deliver web apps with confidence 🚀

28,416

🗃️ Centralized State Management for Vue.js.

60,792

A JS library for predictable global state management

27,458

Simple, scalable state management.

227,213

The library for web and native user interfaces.

Official React bindings for Redux

Quick Overview

The ngrx/platform is a set of libraries for building reactive applications using Angular and RxJS. It provides a state management solution, side-effects management, and more, inspired by the Redux pattern.

Pros

  • Predictable State Management: ngrx/store provides a predictable state container, making it easier to manage the state of your application.
  • Scalable and Testable: The unidirectional data flow and immutable state make the application more scalable and testable.
  • Powerful Side-Effects Management: ngrx/effects allows you to manage side-effects, such as API calls, in a clean and testable way.
  • Reactive Approach: The use of RxJS observables and the reactive programming paradigm make the application more responsive and event-driven.

Cons

  • Steep Learning Curve: The ngrx ecosystem can have a steep learning curve, especially for developers new to the Redux pattern and RxJS.
  • Boilerplate Code: Implementing ngrx can require writing a significant amount of boilerplate code, which can be time-consuming.
  • Performance Concerns: The immutable state and the use of RxJS observables can lead to performance concerns, especially in large-scale applications.
  • Dependency on Angular: ngrx is tightly coupled with the Angular framework, which may limit its use in non-Angular projects.

Code Examples

Here are a few code examples demonstrating the usage of ngrx/platform:

1. Creating a Store

import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';

@NgModule({
  imports: [
    StoreModule.forRoot({ count: counterReducer })
  ]
})
export class AppModule {}

This code sets up the ngrx/store with a counterReducer for the count state.

2. Dispatching an Action

import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';

@Component({
  selector: 'app-counter',
  template: `
    <button (click)="increment()">Increment</button>
    <button (click)="decrement()">Decrement</button>
    <button (click)="reset()">Reset</button>
    <h1>Current Count: {{ count$ | async }}</h1>
  `
})
export class CounterComponent {
  count$ = this.store.select('count');

  constructor(private store: Store<{ count: number }>) {}

  increment() {
    this.store.dispatch(increment());
  }

  decrement() {
    this.store.dispatch(decrement());
  }

  reset() {
    this.store.dispatch(reset());
  }
}

This component demonstrates how to dispatch actions to update the store's state.

3. Managing Side-Effects with Effects

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { map, mergeMap, catchError } from 'rxjs/operators';
import { MyService } from './my.service';

@Injectable()
export class MyEffects {
  loadData$ = createEffect(() =>
    this.actions$.pipe(
      ofType('[My Component] Load Data'),
      mergeMap(() =>
        this.myService.fetchData().pipe(
          map((data) => ({ type: '[My API] Data Loaded', payload: data })),
          catchError((error) => of({ type: '[My API] Data Load Error', payload: error }))
        )
      )
    )
  );

  constructor(private actions$: Actions, private myService: MyService) {}
}

This example demonstrates how to use ngrx/effects to manage side-effects, such as API calls, in a clean and testable way.

Getting Started

To get started with ngrx/platform, follow these steps:

  1. Install the required packages:

Competitor Comparisons

95,657

Deliver web apps with confidence 🚀

Pros of Angular

  • Comprehensive framework with built-in features for routing, forms, and HTTP
  • Extensive documentation and large community support
  • Integrated CLI for easy project setup and management

Cons of Angular

  • Steeper learning curve due to its complexity
  • Larger bundle size, potentially impacting initial load times
  • More opinionated, which may limit flexibility in some cases

Code Comparison

Angular (component example):

@Component({
  selector: 'app-root',
  template: '<h1>{{ title }}</h1>'
})
export class AppComponent {
  title = 'My Angular App';
}

NgRx (store action example):

export const increment = createAction('[Counter] Increment');
export const decrement = createAction('[Counter] Decrement');
export const reset = createAction('[Counter] Reset');

Key Differences

  • Angular is a full-featured framework, while NgRx is a state management library for Angular applications
  • NgRx focuses on predictable state management using Redux patterns, while Angular provides a broader set of tools for building applications
  • Angular includes its own dependency injection system, whereas NgRx relies on Angular's DI for integration

Use Cases

  • Choose Angular for building complete web applications with a structured, opinionated approach
  • Opt for NgRx when you need robust state management in large-scale Angular applications with complex data flows
28,416

🗃️ Centralized State Management for Vue.js.

Pros of Vuex

  • Simpler learning curve and easier to set up for small to medium-sized applications
  • Tighter integration with Vue.js ecosystem and tooling
  • More concise and less boilerplate code required for basic state management

Cons of Vuex

  • Less scalable for large, complex applications compared to NgRx
  • Fewer built-in features for handling side effects and asynchronous operations
  • Limited TypeScript support compared to NgRx's strong typing

Code Comparison

Vuex:

const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state) { state.count++ }
  }
})

NgRx:

export const counterReducer = createReducer(
  initialState,
  on(increment, (state) => ({ ...state, count: state.count + 1 }))
);

Both Vuex and NgRx are state management libraries for their respective frameworks (Vue.js and Angular). Vuex offers a more straightforward approach, making it easier to get started with state management in Vue applications. It has a gentler learning curve and requires less boilerplate code.

On the other hand, NgRx provides a more robust and scalable solution for larger Angular applications. It offers better TypeScript support and more advanced features for handling complex state management scenarios, including powerful tools for managing side effects and asynchronous operations.

The code comparison shows the difference in syntax and structure between the two libraries. Vuex uses a more centralized store configuration, while NgRx employs a more functional approach with reducers and actions.

60,792

A JS library for predictable global state management

Pros of Redux

  • Framework-agnostic, can be used with any JavaScript library or framework
  • Simpler learning curve for developers new to state management
  • Larger ecosystem with more middleware and extensions available

Cons of Redux

  • More boilerplate code required for setup and actions
  • Less type safety out of the box compared to NgRx
  • Manual implementation of side effects, unlike NgRx's built-in Effects system

Code Comparison

Redux:

const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    default:
      return state
  }
}

NgRx:

export const counterReducer = createReducer(
  0,
  on(increment, (state) => state + 1)
);

Redux requires more explicit action handling in the reducer, while NgRx uses a more concise syntax with the createReducer and on functions. NgRx also provides better TypeScript integration out of the box.

Both libraries follow similar principles of immutable state and unidirectional data flow, but NgRx is specifically designed for Angular applications, offering tighter integration with the framework. Redux, being more flexible, can be used in various JavaScript environments but may require additional setup for optimal use in Angular projects.

27,458

Simple, scalable state management.

Pros of MobX

  • Simpler learning curve and less boilerplate code
  • More flexible and less opinionated approach to state management
  • Automatic tracking of observables, reducing manual work

Cons of MobX

  • Less predictable state changes due to mutable state
  • Potential for overuse of observables, leading to performance issues
  • Lack of built-in dev tools compared to NgRx's time-travel debugging

Code Comparison

MobX:

import { observable, action } from 'mobx';

class Store {
  @observable count = 0;
  @action increment() {
    this.count++;
  }
}

NgRx:

import { createAction, createReducer, on } from '@ngrx/store';

export const increment = createAction('[Counter] Increment');
export const counterReducer = createReducer(
  0,
  on(increment, (state) => state + 1)
);

MobX uses decorators and mutable state, allowing for more concise code. NgRx follows a more structured approach with actions and reducers, promoting immutability and predictability.

Both libraries offer powerful state management solutions, but MobX focuses on simplicity and flexibility, while NgRx provides a more robust and structured approach, especially suitable for larger applications with complex state management needs.

227,213

The library for web and native user interfaces.

Pros of React

  • Larger ecosystem and community support
  • More flexible and can be used with various state management solutions
  • Easier learning curve for beginners

Cons of React

  • Requires additional libraries for state management in large applications
  • Less opinionated, which can lead to inconsistent code patterns across projects
  • More boilerplate code needed for complex state management

Code Comparison

React component:

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

NgRx component and store:

@Component({
  template: `
    <p>Count: {{ count$ | async }}</p>
    <button (click)="increment()">Increment</button>
  `
})
export class CounterComponent {
  count$ = this.store.select(selectCount);
  constructor(private store: Store) {}
  increment() {
    this.store.dispatch(increment());
  }
}

Summary

React is a more versatile library with a larger ecosystem, making it suitable for various project sizes and types. It's easier to learn but requires additional setup for complex state management. NgRx, part of the platform repository, provides a more structured approach to state management in Angular applications, with built-in tools for handling complex application states, but has a steeper learning curve.

Official React bindings for Redux

Pros of react-redux

  • Simpler learning curve due to less boilerplate and fewer concepts
  • More flexible and adaptable to different project structures
  • Larger ecosystem and community support

Cons of react-redux

  • Less opinionated, which can lead to inconsistent implementations
  • Lacks built-in effects handling and entity management
  • Manual implementation of features like memoization and selectors

Code Comparison

react-redux:

const mapStateToProps = state => ({
  todos: state.todos
});

const mapDispatchToProps = dispatch => ({
  addTodo: text => dispatch(addTodo(text))
});

export default connect(mapStateToProps, mapDispatchToProps)(TodoList);

ngrx/platform:

@Component({
  selector: 'app-todo-list',
  template: `...`
})
export class TodoListComponent {
  todos$ = this.store.select(selectTodos);
  constructor(private store: Store) {}
  addTodo(text: string) {
    this.store.dispatch(addTodo({ text }));
  }
}

The react-redux example uses the connect higher-order component to map state and dispatch to props, while ngrx/platform leverages Angular's dependency injection and RxJS observables for a more declarative approach. ngrx/platform provides a more structured and opinionated way of managing state, which can lead to more consistent codebases in larger projects.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

@ngrx

Reactive State for Angular

CircleCI Join the discord server at https://discord.com/invite/ngrx Commitizen friendly npm version

Documentation

Check out our website: ngrx.io.

Contributing

NgRx is a community-driven project. Read our contributing guidelines on how to get involved.

Sponsoring NgRx

Sponsorships aid in the continued development and maintenance of NgRx libraries, along with supporting core contributors on the project. Consider asking your company to sponsor NgRx as its core to their business and application development.

Gold Sponsors

NxDevTools logo

Become a gold sponsor and get your logo on our README on GitHub and the front page of ngrx.io.

Silver Sponsors

Become a silver sponsor and get your logo on our README on GitHub.

Bronze Sponsors

House of Angular

Become a bronze sponsor and get your logo on our README on GitHub.

Enterprise Support

If your team or your company is looking for more hands-on support such as training or workshops, check out our Enterprise Support page.

NPM DownloadsLast 30 Days