DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Angular Signal Effect

Image description

A Signal is a wrapper around a value that can notify affected consumers when that value changes.

But what if something happens when a Signal is modified?

That's where Effect comes in.

Effects are performed only when the value of a signal within it changes.

When an Effect is executed, it keeps track of any reading of the Signal value. Each time one of these values changes, the Effect is executed again.

Let's say that in behavior they are similar to signal computed.
There are just a few things to keep in mind with Effect:
🌟 They must be created within the constructor or in a component property.
🌟 Effects are always executed asynchronously, during the Change Detection process.

In addition, Effects were created to handle certain cases, not to change the State of a component or application.

The use cases are as follows:
🌟 To perform Data Logging.
🌟 To keep data synchronized with localStorage.
🌟 To add custom behaviors to the DOM.

Trying to update a Signal within an effect() is not allowed by default, as it could trigger unwanted behavior (infinite loop such as SignalA triggers update of SignalB that updates SignalC that updates SignalA - and around we go).

That said, if you know what you're doing and are 100% sure that you won't trigger an infinite loop, you can override that setting with the optional parameter allowSignalWrites as follows:

Image description

Conclusion:
Effects are very powerful, but you have to be careful how you use them.
Example here: https://stackblitz-starters-yzbh3d.stackblitz.io/


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (0)