tezvyn:

NgRx Store: Reactive State Management for Angular

AI-drafted, machine-checkedSource: ngrx.iointermediate

NgRx Store is a centralized database for your Angular app's frontend state, providing a single source of truth. Use it in large apps to manage complex, shared state like user sessions. The main footgun is overusing it for simple, local state.

WHY IT EXISTS In large Angular applications, managing state that's shared across many components can become chaotic. Passing data through inputs and outputs gets complex, and shared services can become unpredictable stateful bags. NgRx Store provides a structured, predictable pattern for managing this shared, or "global", state.

THE MENTAL MODEL Think of the NgRx Store as your application's client-side database. It's a single, immutable object representing your entire app's state. You don't modify this database directly. Instead, you dispatch "actions"—events describing what happened. "Reducers"—pure functions—then calculate the new state based on the current state and the action. Components subscribe to slices of this state and reactively update when it changes.

HOW IT WORKS The flow is unidirectional. First, a component dispatches an action (e.g., 'Load Products'). Second, an optional side-effect handler called an Effect can listen for this action to perform tasks like API calls, dispatching a new success or failure action upon completion. Third, a reducer function receives the action and returns a completely new state object, never modifying the old one. Finally, components using "selectors" to query the store receive the new state via an Observable and update their view.

WHEN TO USE IT Use NgRx Store for complex, shared state that needs to be accessed by many unrelated components in a large application. It's ideal for things like user authentication status, shopping cart contents, or data that needs to persist across different routes. It helps you architect complex apps for long-term success.

WHEN NOT TO USE IT Avoid NgRx for state that is purely local to a single component, like the open/closed state of a dropdown or form data that doesn't need to be shared. The boilerplate of creating actions, reducers, and effects is significant overkill for these simple use cases. A standard Angular service or simple component state is often a better choice.

ONE CANONICAL EXAMPLE Managing user authentication. A feature state might hold isLoggedIn: boolean and user: object. A login component dispatches a [Login Page] Login action. An AuthEffects class calls the auth API and dispatches [Auth API] Login Success with user data. The authReducer updates the state. A navbar and a profile page can both select isLoggedIn to reactively show or hide content without ever communicating directly.

Read the original → ngrx.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.