🅰️ Angular Intermediate

What is the Angular NgRx state management library?

Answer

NgRx is Angular's implementation of the Redux pattern using RxJS. It provides a reactive state management solution for complex Angular applications. Core principles: single immutable state tree, state changed only by pure functions (reducers), all state changes flow through dispatched actions. Core concepts: (1) Store: the single source of truth — a RxJS BehaviorSubject holding the entire app state. Access: this.store.select(selectUsers); (2) Actions: descriptive events that describe what happened: export const loadUsers = createAction("[Users] Load Users"); export const loadUsersSuccess = createAction("[Users] Load Users Success", props<{ users: User[] }>());; (3) Reducers: pure functions that compute the new state: const usersReducer = createReducer(initialState, on(loadUsersSuccess, (state, { users }) => ({ ...state, users, loading: false })));; (4) Selectors: memoized functions to derive state slices: export const selectUsers = createSelector(selectUsersState, state => state.users);; (5) Effects: handle side effects (HTTP calls) — listen for actions, perform async operations, dispatch new actions: loadUsers$ = createEffect(() => this.actions$.pipe(ofType(loadUsers), switchMap(() => this.http.get<User[]>("/api/users").pipe(map(users => loadUsersSuccess({ users })), catchError(error => of(loadUsersFailure({ error }))))))));. When to use: complex state shared across many components, complex state transitions, need for time-travel debugging. For simpler state, use Angular services with BehaviorSubject.