Return to site

React useState() vs. Angular signal()

· react

The React 18 useState() hook and the Angular 16 Signal feature are both ways of managing state in functional components. However, they have some differences in how they work and what they offer.

Differences:

Here are some of the main differences:

React Snippet showing a counter with useState()

import { useState } from "react";

const Counter = (props) => {
  // Define a state variable for the count and initialize it to 0
  const [count, setCount] = useState(0);

  // Define a function to increment the count by 1
  function increment() {
    // Update the count by passing a new value
    setCount(count + 1);
  }

  // Define a function to decrement the count by 1
  function decrement() {
    // Update the count by passing a function that returns a new value
    setCount((prevCount) => prevCount - 1);
  }

  return (
    <div>
      <p>The count is: {count}</p>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
};

export default Counter;

Links to practice courses: React, Angular

import { Component } from "@angular/core";
import { signal, computed }from '@angular/core';

@Component({
  selector: "my-counter",
  template: `
    <div>
      <p>The count is: {{ count() }}</p>
      <p>The double count is: {{ doubleCount() }}</p>
      <button (click)="increment()">+</button>
      <button (click)="decrement()">-</button>
    </div>
  `,
})
export class CounterComponent {
  // Define a writable signal for the count and initialize it to 0
  count = signal(0);

  // Define a computed signal for the double count that depends on the count
  doubleCount = computed(() => this.count() * 2);

  // Define a method to increment the count by 1
  increment() {
    // Update the count by using the update method
    this.count.update((value) => value + 1);
  }

  // Define a method to decrement the count by 1
  decrement() {
    // Update the count by using the set method
    this.count.set(this.count() - 1);
  }
}