What is Action in NgRx: Simple Explanation and Example
action is a plain object that describes an event or intention to change the state in your Angular app. Actions are dispatched to trigger state updates handled by reducers and effects.How It Works
Think of an action in NgRx like sending a message that something happened or should happen in your app. For example, when a user clicks a button to load data, an action is sent to say "start loading data".
This action is a simple object with a type property describing what happened, and optionally some extra information called payload. The NgRx store listens for these actions and uses reducers to decide how to update the app's state based on the action type.
It’s like a postman delivering messages (actions) to a manager (reducer) who updates the company records (state) accordingly. This keeps your app’s state predictable and easy to follow.
Example
This example shows how to define and dispatch an action to load user data in NgRx.
import { createAction, props } from '@ngrx/store'; // Define an action with a type and optional payload export const loadUser = createAction( '[User Page] Load User', props<{ userId: string }>() ); // Dispatching the action in a component import { Component } from '@angular/core'; import { Store } from '@ngrx/store'; import { loadUser } from './user.actions'; @Component({ /* component metadata */ }) export class UserComponent { constructor(private store: Store) {} loadUserData(id: string) { this.store.dispatch(loadUser({ userId: id })); } }
When to Use
Use actions whenever you want to represent an event that changes your app’s state or triggers side effects. This includes user interactions like clicks, API calls starting or finishing, or any event that should update the UI.
For example, when a user logs in, you dispatch a login action. When data loads successfully, you dispatch a success action with the data. This clear flow helps keep your app organized and easy to debug.
Key Points
- Actions are plain objects describing events or intentions.
- They have a
typeand optionalpayload. - Dispatching actions triggers state changes via reducers.
- They help keep state changes predictable and traceable.
- Use
createActionfrom NgRx to define actions cleanly.