Angular NgRX
NgRx Basics – Simple Guide for Angular Developers
📌 What is NgRx?
NgRx is a state management library for Angular that helps you manage and share data across your application in a structured and predictable way.
It follows the Redux pattern, where all the application state is stored in a single place called the Store.
🧠 Why Do We Need NgRx?
In small Angular apps:
You can manage data using services
But in large apps:
Data flows between many components
Hard to track changes
Debugging becomes difficult
👉 NgRx solves this by:
Centralizing data
Making data flow predictable
Improving maintainability
⚡ Key Concepts of NgRx
1. Store
Central place where all application state is stored
Acts as a single source of truth
2. Actions
Events that describe what happened
Example:
export const loadUsers = createAction('[User] Load Users');
👉 Think: “Something happened in the app”
3. Reducers
Functions that update the state based on actions
Example:
const initialState = { users: [] };
const userReducer = createReducer(
initialState,
on(loadUsersSuccess, (state, { users }) => ({
...state,
users
}))
);
👉 Reducers must be pure functions
4. Effects
Handle asynchronous operations like API calls
Example:
loadUsers$ = createEffect(() =>
this.actions$.pipe(
ofType(loadUsers),
switchMap(() => this.userService.getUsers()
.pipe(
map(users => loadUsersSuccess({ users }))
)
)
)
);
👉 Effects = side effects (API, async logic)
5. Selectors
Used to read data from the store
Example:
export const selectUsers = (state) => state.users;
👉 Components use selectors to get data
🔁 Data Flow in NgRx
Without API:
Component → Action → Reducer → Store → UI Update
With API:
Component → Action → Effect → API → Reducer → Store → UI Update
👉 This flow is predictable and easy to debug
🧩 Simple Example (User Fetch Flow)
Component dispatches action:
this.store.dispatch(loadUsers());
Effect calls API
Reducer updates store with users
Component subscribes using selector:
this.users$ = this.store.select(selectUsers);
🧠 Advantages of NgRx
Centralized state management
Predictable data flow
Easier debugging
Better scalability
Useful for large applications
🚨 When NOT to Use NgRx
Avoid NgRx if:
Your app is small
Data flow is simple
Few components share state
👉 It can add unnecessary complexity
⚡ NgRx vs Angular Services
| Feature | Angular Service | NgRx |
|---|---|---|
| Simplicity | Easy | Complex |
| Scalability | Limited | High |
| State Control | Loose | Strict |
| Debugging | Hard | Easier |
🧭 When Should You Use NgRx?
Use NgRx when:
Multiple components share data
App is large and complex
You need strict state control
🔥 Final Summary
NgRx helps manage state in Angular apps
Uses Store, Actions, Reducers, Effects, Selectors
Best for large-scale applications
Not needed for small apps
🧠 Key Mindset
NgRx is not about writing more code
It’s about writing predictable and maintainable code
Comments
Post a Comment