What is Effect in Angular Signals: Explanation and Example
effect in Angular signals is a function that runs automatically whenever the signals it depends on change. It helps you react to changes by running side effects like updating the UI or calling APIs without manually tracking dependencies.How It Works
Think of effect as a watcher that listens to changes in certain values called signals. When any of these signals change, the effect runs a block of code automatically. This is like having a smart assistant who notices when something important changes and then takes action for you.
For example, if you have a signal holding a number and you want to log it every time it changes, you create an effect that depends on that signal. Whenever the number updates, the effect runs and logs the new value. This way, you don't have to manually check or call functions; Angular handles it for you.
Example
import { signal, effect } from '@angular/core'; const count = signal(0); effect(() => { console.log('Count changed to:', count()); }); count.set(1); count.set(2);
When to Use
Use effect when you want to run code automatically in response to changes in signals. This is useful for side effects like:
- Updating the UI outside Angular templates
- Calling APIs when data changes
- Logging or debugging signal changes
- Synchronizing state with external systems
It helps keep your code clean by separating reactive logic from manual event handling.
Key Points
- effect runs automatically when signals it reads change.
- It tracks dependencies inside its function without manual setup.
- Useful for side effects, not for returning values.
- Helps keep reactive code simple and clear.
Key Takeaways
effect runs code automatically when dependent signals change.