Sitemap
The 60-Second Programmer

Quick, actionable programming tips and insights delivered in just 60 seconds. Perfect for developers who want to learn on the go. Whether you’re a beginner or seasoned pro, our bite-sized lessons fit your schedule and boost your coding skills fast!

State Management in Angular: NgRx vs Services 🔄

2 min readSep 24, 2024

--

Managing state in an Angular application can become complex as your app grows. Angular provides multiple ways to handle state: using services or the NgRx library for more advanced state management.

Press enter or click to view image in full size

Using Services for State Management 🛠️

In small or simple applications, you can manage state using Angular services. Services act as singletons, meaning the same instance of a service is shared across your application. Here’s an example:

@Injectable({
providedIn: 'root',
})
export class CounterService {
private counter = 0;

increment() {
this.counter++;
}

getCounter() {
return this.counter;
}
}

In this example, the service holds and manages the state of a simple counter.

NgRx for Advanced State Management 📦

For more complex applications, NgRx is a powerful library based on Redux that provides a more structured way to manage application state. It uses actions, reducers, and stores to manage state changes.

Get Marcelo Domingues’s stories in your inbox

Join Medium for free to get updates from this writer.

Example of a basic NgRx setup:

Define Actions:

export const increment = createAction('[Counter Component] Increment');

Create a Reducer:

export const counterReducer = createReducer(0,
on(increment, (state) => state + 1)
);

Access the Store:

this.store.select('counter').subscribe(count => {
this.counter = count;
});

Conclusion

Use services for simple state management and NgRx when your application grows more complex, especially when you need to manage shared state across many components. 🔧

--

--

Marcelo Domingues
Marcelo Domingues

Written by Marcelo Domingues

🚀 Lead Software Engineer for Siemens | Crafting Code & Words | Empowering Tech Enthusiasts ✨ 📲 LinkedIn: https://www.linkedin.com/in/marcelogdomingues/

The 60-Second Programmer
The 60-Second Programmer

Published in The 60-Second Programmer

Quick, actionable programming tips and insights delivered in just 60 seconds. Perfect for developers who want to learn on the go. Whether you’re a beginner or seasoned pro, our bite-sized lessons fit your schedule and boost your coding skills fast!