0
0
AngularConceptBeginner · 3 min read

What is Action in NgRx: Simple Explanation and Example

In NgRx, an 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.

typescript
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 }));
  }
}
Output
No visible output; the action triggers state changes handled by reducers.
🎯

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 type and optional payload.
  • Dispatching actions triggers state changes via reducers.
  • They help keep state changes predictable and traceable.
  • Use createAction from NgRx to define actions cleanly.

Key Takeaways

An action in NgRx is a simple object that signals a state change or event.
Use actions to represent user events, API calls, or any state updates.
Actions have a type and optional data payload to describe what happened.
Reducers listen to actions to update the app state predictably.
Define actions with NgRx's createAction for clear and maintainable code.