I'm trying to understand component re-rendering in react vs. angular. My understanding is as follows:
React uses Virtual DOM. This is an object in memory that models the DOM. Each time some state changes, the new object is compared to a snapshot of the old component. Those changes are then synced with the real DOM, with only the affected nodes being changed.
Angular uses incremental DOM. This is also some object in memory that models the DOM, but the object is updated in place on object changes. Those changes are then also synced with the real DOM, with only the affected nodes being changed.
What I don't understand is why react components constantly re-render. For example the following:
export const myComponent = () => {
const [state, setState] = useState(1);
const onClick = () => {
setState(state + 1);
};
console.log("re-render");
return (
<>
<h1>My Component</h1>
<button onClick={onClick}>The button has been clicked: {state} time(s)</button>
</>
);
}
will cause the entire component to be re-rendered every time.
However, with a similar angular component, where the html is as follows:
<h1>My Component</h1>
<button click="onClick()">click here</button>
and the ts is as follows:
export class ExampleComponent implements OnInit {
buttonClick : int
constructor() { this.buttonClick = 0 }
ngOnInit() { }
onClick() {
this.buttonClick += 1
}
}
the component will not re-render. Only the html binding will be updated.
Is my understanding correct? If so, why do react components re-render constantly? Does this have anything to do with the Virtual DOM vs. Incremental DOM? Or is it just the way the react and angular are designed?
Thanks!