What Happens When Application State Changes?

1. How Angular Handles Change Detection

Angular uses change detection to determine whether changes in application state affect the values displayed in the template.

When a value changes, Angular evaluates the relevant template bindings and updates the DOM where necessary.

For example:

import { Component } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <h2>Count: {{ count }}</h2>
    <button (click)="increment()">Increment</button>
  `
})
export class CounterComponent {
  count = 0;

  increment() {
    this.count++;
  }
}

When the user clicks the button, Angular updates the count property and runs the appropriate change-detection process. The displayed count is then updated in the DOM.

Angular provides several mechanisms to improve this process:

  • Signals: Make state reactive and help Angular track dependencies that need updating.

  • OnPush: Reduces unnecessary component checks by using specific triggers to determine when a component should be checked.

  • Zoneless change detection: Allows Angular to schedule updates without relying on Zone.js to detect asynchronous activity.

These features help developers build applications that remain responsive as their complexity grows.

2. How React Handles Rendering

React follows a different approach. When state changes, React can re-render the affected component to calculate what the UI should look like.

Consider the following example:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </>
  );
}

export default Counter;

When the button is clicked, setCount() schedules a state update. React renders the component again, compares the resulting UI representation with the previous one, and commits the necessary changes to the DOM.

React uses two important concepts:

  • Rendering: Calculates the next UI based on the current props and state.

  • Reconciliation: Determines what has changed between the previous and next UI representations.

React can also skip some rendering work through techniques such as React.memo, useMemo, and useCallback, when their use is appropriate.