0
0
Angularframework~3 mins

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

Choose your learning style9 modes available
The Big Idea

Discover how to make your app handle side tasks automatically and avoid messy, buggy code!

The Scenario

Imagine you have to manually watch for every change in your app's data and then write code to update the UI, fetch new data, or save changes to a server.

You have to add event listeners everywhere and carefully manage when and how these side tasks run.

The Problem

This manual approach is tiring and error-prone because you might forget to update something or cause unexpected bugs by running side tasks too often or too late.

It becomes hard to keep track of all these side effects as your app grows.

The Solution

Effects in Angular let you declare side effects separately and react automatically to changes in your app's state.

This keeps your code clean, predictable, and easier to maintain because side effects run only when needed.

Before vs After
Before
store.subscribe(() => { if (store.state.changed) { fetchData(); } });
After
createEffect(() => this.actions$.pipe(ofType(loadData), switchMap(() => fetchData())));
What It Enables

It enables automatic, clean, and reliable handling of side effects triggered by app state changes without cluttering your main logic.

Real Life Example

When a user clicks a button to load data, Effects automatically fetch the data from the server and update the app without you writing complex manual subscriptions.

Key Takeaways

Manual side effect handling is complex and error-prone.

Effects separate side effects from main logic for clarity.

They run automatically when app state changes, improving reliability.