I recently reviewed some code where detectChanges
is called. I've read all over the place that manually running a change detection cycle is a code smell and a sign that you are probably doing something wrong. I've personally never had to use it in this project, but I can't really argue WHY it's bad. The best I can come up with is "You shouldn't be manually doing what Angular does automatically", but I want to have a better answer than that. What could go wrong if I call detectChanges
? Can you provide some examples?
Asked
Active
Viewed 135 times
2

Cory
- 51
- 2
-
I think the StackExchange CodeReview would be a better place for this one, but that being said; I think you already gave yourself the answer and why would you need examples. Angular already does detectChanges, so why would you want to do it again? – riffnl Jan 05 '22 at 23:51
-
I agree that you wouldn't want to do it again, but it's often suggested as a solution to some edge cases, for example, if a lifecycle hook changes component state and you need to run another change detection cycle. Furthermore, the Angular Components library calls detectChanges in about a dozen places, so there are use cases for it. Saying, "It's unnecessary" is a sufficient reason to remove it from code that works otherwise, but if detectChanges fixes an issue, what are potential side effects from using it? – Cory Jan 06 '22 at 00:03
-
There aren't any :) but again: you've given yourself an answer, if it's needed to fix a problem, use it - but also (that might be important) document why it's needed, that will also save you a lot of time explaining (since it's already in the code for everyone to see) - but it's also the reason I mentioned this should've been posted on CodeReview :D – riffnl Jan 06 '22 at 00:06