RosettaJS: Comparativas de Vue, React y Angular

State and Reactivity

Reacting to State Changes

There are tools that let you manage side effects in response to application state changes.

Example

Showing an alert when a user logs in.

Vuewatch()

<script setup lang="ts">
import { ref, watch } from 'vue'

const logged = ref(false)

watch(
  logged,
  (isLogged) => {
    if (isLogged) {
      alert('User is logged')
    }
  },
  { immediate: true },
)
</script>

<template>
  <button @click="logged = true">Log in</button>
</template>

It uses the watch() function, which lets you observe a reactive source. With immediate: true, it also runs the check on initialization.

ReactuseEffect()

import { useEffect, useState } from 'react'

function LoggedAlert() {
  const [logged, setLogged] = useState(false)

  useEffect(() => {
    if (logged) {
      alert('User is logged')
    }
  }, [logged])

  return <button onClick={() => setLogged(true)}>Log in</button>
}

When using the useEffect() Hook, the check runs after the first render and when its dependencies change.

Angulareffect()

import { Component, effect, signal } from '@angular/core'

@Component({
  selector: 'app-logged-alert',
  standalone: true,
  template: `
    <button (click)="logIn()">Log in</button>
  `,
})
export class LoggedAlertComponent {
  logged = signal(false)

  constructor() {
    effect(() => {
      if (this.logged()) {
        alert('User is logged')
      }
    })
  }

  logIn() {
    this.logged.set(true)
  }
}

The effect() function reacts to the signals it reads. It runs initially and when they change.