- Published on
Angular Signal Effect
- Authors
- Name
Photo by James Harrison on Unsplash
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 the 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 specific 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 an 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:
Conclusion:
Effects are potent, but you must 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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/