0
0
Angularframework~10 mins

Actions and reducers pattern in Angular - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Actions and reducers pattern
User triggers action
Action dispatched
Reducer receives action
Reducer updates state
New state emitted
UI updates with new state
This flow shows how an action triggers a reducer to update the state, which then updates the UI.
Execution Sample
Angular
import { createAction, createReducer, on } from '@ngrx/store';

const increment = createAction('Increment');

const counterReducer = createReducer(
  0,
  on(increment, state => state + 1)
);
This code defines an increment action and a reducer that increases the state by 1 when the action is dispatched.
Execution Table
StepAction DispatchedState BeforeReducer LogicState AfterUI Update
1increment0state + 11Counter shows 1
2increment1state + 12Counter shows 2
3increment2state + 13Counter shows 3
4No action3No change3Counter remains 3
💡 No action dispatched, so state remains unchanged and UI does not update.
Variable Tracker
VariableStartAfter 1After 2After 3Final
state01233
Key Moments - 2 Insights
Why does the state not change if no action is dispatched?
Because reducers only update state when they receive a matching action, as shown in step 4 of the execution_table where no action means no state change.
What happens inside the reducer when an action is dispatched?
The reducer runs its logic for that action, here adding 1 to the current state, as seen in steps 1-3 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state after step 2?
A1
B3
C2
D0
💡 Hint
Check the 'State After' column at step 2 in the execution_table.
At which step does the UI show the counter as 3?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'UI Update' column in the execution_table.
If we dispatch the increment action twice more after step 3, what will the state be?
A4
B5
C3
D6
💡 Hint
Each increment adds 1 to the state; after 3 it is 3, so two more increments add 2.
Concept Snapshot
Actions and reducers pattern in Angular:
- Action: a plain event describing what happened.
- Reducer: a pure function updating state based on action.
- Dispatch action to trigger reducer.
- Reducer returns new state.
- UI updates automatically with new state.
Full Transcript
In Angular, the actions and reducers pattern helps manage state changes clearly. When a user triggers an action, it is dispatched to the reducer. The reducer receives the current state and the action, then returns a new state based on the action's logic. This new state updates the UI. For example, an increment action increases a counter state by one each time it is dispatched. If no action is dispatched, the state stays the same. This pattern keeps state predictable and easy to follow.