0
0
Angularframework~3 mins

Why Effect for side effects in Angular? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your app react perfectly to changes without messy code!

The Scenario

Imagine you want to run some code whenever a user clicks a button or when some data changes, like logging a message or fetching new information.

You try to do this by manually watching for changes and calling functions everywhere in your code.

The Problem

Manually tracking when to run side actions is tricky and easy to forget.

You might run the code too many times or miss running it at all, causing bugs and confusing behavior.

The Solution

Angular's Effect lets you declare side effects clearly and automatically runs them when needed.

This keeps your code clean and reliable, so side actions happen exactly when they should.

Before vs After
Before
button.addEventListener('click', () => { console.log('Clicked!'); fetchData(); });
After
effect(() => { if (signal()) { console.log('Clicked!'); fetchData(); } });
What It Enables

You can easily run side actions tied to state changes without messy manual checks.

Real Life Example

When a user toggles a switch, you want to save their preference and update the UI smoothly without extra event wiring.

Key Takeaways

Manual side effect handling is error-prone and hard to maintain.

Effect provides a clear, automatic way to run side actions in Angular.

This leads to cleaner code and better app behavior.