What is NgRx?
NgRx is a group of libraries inspired by Redux that provides reactive state management for Angular applications. It centers around a 'Store'—a single, immutable database that lives in the browser's memory. As an Architect, you use NgRx when your application state becomes too complex for simple services, specifically when multiple disconnected parts of the UI need to stay in sync with the same data.
- The Four Pillars of NgRx
To master NgRx, you must understand the four core building blocks that make up its lifecycle.
- Actions: Unique events that happen in the app (e.g., '[Project Page] Load Projects'). They describe what happened, not how the state changes.
- Reducers: Pure functions that listen for Actions. They take the current State and the Action to produce a New State. They never mutate the old state.
- Selectors: Pure functions used to slice and transform specific pieces of state from the store for components to consume.
- Effects: A side-effect model for RxJS. They listen for Actions, perform asynchronous tasks (like calling your Python API), and then dispatch a new Action with the result.
- Implementation Example: Actions & Reducers
In modern NgRx (v15+), we use functional creators to reduce boilerplate. Here is how you would define the state for a Flutter project builder.
- Handling Side Effects
Effects isolate your components from external interactions. Instead of a component calling a service directly, the component dispatches an Action. The Effect catches that Action, calls the API, and returns a 'Success' Action which the Reducer then uses to update the UI.
When to Use NgRx? (The SHARI Principle)
| Factor | Description | Decision |
|---|---|---|
| Shared | State is accessed by many components | Use NgRx |
| Hydrated | State is persisted and rehydrated (LocalStorage) | Use NgRx |
| Available | State is needed when re-entering a route | Use NgRx |
| Retrieved | State is retrieved with side effects (APIs) | Use NgRx |
| Impacted | State is impacted by actions from other sources | Use NgRx |