Should I always use ChangeDetectionStrategy.OnPush
in my components?
I always hear how OnPush
is absolutely amazing, and solves so many issues, speeds up the Angular app, and even get rid of NgZone
. But if it is, why isn't it generated by default with ng g component
?
If it is so amazing, then should we always use it?
The Effect of OnPush The OnPush strategy changes Angular's change detection behavior in a similar way as detaching a component does. The change detection doesn't run automatically for every component anymore.
OnPush means that the change detector's mode will be set to CheckOnce during hydration. Default means that the change detector's mode will be set to CheckAlways during hydration.
By default, Angular 2+ performs change detection on all components (from top to bottom) every time something changes in your app. A change can occur from a user event or data received from a network request.
why isn't it generated by default with ng g component?
It is a design decision that developer needs to make. ChangeDetectionStartegy.OnPush
works well with immutable objects. If you don't use immutable objects, you will be having hard time finding what's going wrong with your component. Since the angular team doesn't force you to use immutable objects why would they generate component with this strategy.
You can read more on ChangeDetection here: Everything you need to know about change detection in Angular
OnPush is designed to work with the components that have @Input()
decorators. In simple words components that take inputs from their parent component. Since change detection is an expensive operation you can configure such components to run change detection only when their input property changes.
A good example for OnPush()
to be used would be a loader component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With