Effects are rarely needed in most application code, but may be useful in specific circumstances. Here are some examples of situations where an effect might be a good solution:
- Logging data being displayed and when it changes, either for analytics or as a debugging tool.
- Keeping data in sync with window.localStorage.
- Adding custom DOM behavior that can't be expressed with template syntax.
- Performing custom rendering to a , charting library, or other third party UI library.
Avoid using effects for propagation of state changes. This can result in ExpressionChangedAfterItHasBeenChecked
errors, infinite circular updates, or unnecessary change detection cycles.
Because of these risks, Angular by default prevents you from setting signals in effects. It can be enabled if absolutely necessary by setting the allowSignalWrites
flag when you create an effect.
Instead, use computed signals to model state that depends on other state.