I understood how change detection works in Angular 5.0.
Can some one help me to understand how the same works in React and how much it was different from Angular's ?
React and Angular’s change detection are different, but they have in common one very important thing - making diff of current and previous state from memory (not from DOM) and rendering only what has been changed.
In Angular, on high level it works like this:
NOTE: Mind that if You use ChangeDetectionStrategy.OnPush, some components and its descendants might be omitted during tree traversal. It can be great optimization.
In React it looks like this:
setState
was called.NOTE: Similar to Angular’s ChangeDetectionStrategy.OnPush, in React we have class React.PureComponent. We can use this class to avoid unnecessary change detection.
Of course there's lot more differences, but on high level, I think those are the most important.
React change detection is more or less the same as Angular, except three things:
1) when to start: the diffing starts whenever a component's setState method is called (whereas Angular does the diffing whenever a Dom event is triggered, whenever a setInterval/setTimeout callback is run, and whenever an ajax callback is run)
2) where to start: the diffing starts from the component that has the setState called, then its children, and down the hierarchy (whereas Angular starts from the very top component)
3) what to compare: the diffing compares the virtual DOM of the current HTML with the virtual DOM after the state change. (whereas Angular uses the data-bound values used in the template, before and after, for comparison)