Introduction to NgRx
Actions, reducers, selectors, and effects — the Redux pattern NgRx brings to Angular, and why it trades simplicity for structure.
Introduction to NgRx
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An action is a plain object describing something that happened — never, by itself, a direct state mutation; a reducer is the only thing that turns an action into a new state.
- A reducer is a pure function: given the current state and an action, it returns a brand-new state object — it never mutates the existing one in place.
- An effect handles the side effects (an HTTP call triggered by an action) that a reducer, being pure, is explicitly not allowed to do itself.
Why reach for more structure than a plain service
The previous lesson ended with a real, working pattern: a service holding signals, mutated through methods, injected wherever needed. NgRx doesn’t replace that idea so much as impose a strict shape on it — the Redux pattern, adapted to Angular — in exchange for guarantees a plain service doesn’t give you for free: every state change traceable to a specific, named action; state that’s genuinely impossible to mutate accidentally from the wrong place; a consistent, predictable structure across an entire large codebase instead of each service inventing its own conventions. That structure costs real ceremony — this is worth being honest about going in, not treated as free.
Actions: a description, not a mutation
export const loadUsers = createAction('[User List] Load Users');
export const loadUsersSuccess = createAction(
'[User List] Load Users Success',
props<{ users: User[] }>(),
);
An action is a plain, serializable object describing that something happened — “load the users,” “the users loaded successfully, here they are.” Dispatching one doesn’t itself change any state; it’s purely a description of an event, broadcast to whatever’s listening. This separation is the entire foundation of the pattern: by making every single state change traceable to a specific, named action, you get a readable history of everything that’s ever happened to the store, instead of mutations scattered invisibly across however many services happen to touch the same data.
Reducers: pure functions, new state every time
export const userReducer = createReducer(
initialState,
on(loadUsers, (state) => ({ ...state, loading: true })),
on(loadUsersSuccess, (state, { users }) => ({ ...state, users, loading: false })),
);
A reducer is the only thing that turns an action into an actual state change —
and it’s required to be a pure function: given the current state and an action,
return a brand-new state object, with no mutation of the existing one and no
side effects of any kind (no HTTP calls, no logging, nothing beyond computing
the next state). { ...state, loading: true } spreads the existing state into
a new object with one field overridden — never state.loading = true, which
would mutate the object other parts of the app might still be holding a
reference to.
Effects: where the side effects NgRx reducers forbid actually go
Reducers being pure and side-effect-free raises an obvious question: something
still has to actually make the HTTP call when a loadUsers action fires.
That’s an effect — code that listens for actions and performs the side
effects reducers explicitly can’t, typically dispatching a follow-up action
(loadUsersSuccess, with the result) once the async work resolves:
loadUsers$ = createEffect(() =>
this.actions$.pipe(
ofType(loadUsers),
switchMap(() => this.userService.getUsers().pipe(
map((users) => loadUsersSuccess({ users })),
)),
),
);
Notice the RxJS operators doing real work here — switchMap for exactly the
reason covered in the RxJS section earlier in this roadmap. Effects are where
NgRx and RxJS meet most directly: an effect is, structurally, an observable
pipeline reacting to a stream of dispatched actions.
Selectors: reading state back out
export const selectUsers = (state: AppState) => state.users.users;
export const selectUserCount = createSelector(selectUsers, (users) => users.length);
A selector is how a component reads state back out of the store — and
createSelector memoizes its result the same way computed() memoizes a
derived signal, recalculating only when the underlying state it depends on
actually changes.
This lesson’s video builds all four pieces — actions, reducers, effects, selectors — together on a real API-backed example, which is the only way this pattern genuinely clicks; the linked “deeper” video, from a well-known Angular educator, is a second, differently-paced explanation of the same four concepts if the first pass needs reinforcing.
Check yourself
Why does dispatching `loadUsers()` as an action not, by itself, change anything in the store?
An action is just a plain object describing that something happened — it carries no logic to change state on its own. Only a reducer, listening for that specific action, decides what the new state should be in response. Dispatching an action with no reducer handling it changes nothing at all, which is a common early point of confusion.
What would be wrong with a reducer that does `state.users.push(newUser); return state;` instead of `return { ...state, users: [...state.users, newUser] };`?
The first mutates the existing state object in place rather than returning a new one — which breaks the pure-function contract reducers are built on, and breaks change detection relying on reference equality (the same OnPush reference-comparison issue from earlier in this roadmap) along with NgRx's own ability to track state changes over time for things like time-travel debugging. The second creates an entirely new object, leaving the original untouched.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.