State and Reactivity
Object State
Object state lets you group several related properties inside a single reactive structure.
Example
Updating a person's age inside a state object.
Vuereactive
<script setup lang="ts">
import { reactive } from 'vue';
const user = reactive({
name: 'Alex',
age: 28,
});
function incrementAge() {
user.age++;
}
</script>
<template>
<button @click="incrementAge">
{{ user.name }}: {{ user.age }}
</button>
</template>
It uses reactive to group related properties inside the same reactive object.
ReactuseState
import { useState } from 'react';
function UserCard() {
const [user, setUser] = useState({
name: 'Alex',
age: 28,
});
function incrementAge() {
setUser({
...user,
age: user.age + 1,
});
}
return (
<button onClick={incrementAge}>
{user.name}: {user.age}
</button>
);
}
It stores the whole object with useState and creates a new copy when one property is updated.
Angularsignal
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-user-card',
standalone: true,
template: `
<button (click)="incrementAge()">
{{ user().name }}: {{ user().age }}
</button>
`
})
export class UserCardComponent {
user = signal({
name: 'Alex',
age: 28,
});
incrementAge() {
this.user.update((currentUser) => ({
...currentUser,
age: currentUser.age + 1,
}));
}
}
It stores the object in a signal and creates a new object when one of its properties is updated.
