State and Reactivity
Computed Values
Computed values let you calculate a value from other reactive values without storing it as separate state.
Example
Updating a quantity and showing a total calculated automatically.
Vuecomputed
<script setup lang="ts">
import { computed, ref } from 'vue'
const price = ref(8)
const quantity = ref(1)
const total = computed(() => price.value * quantity.value)
function incrementQuantity() {
quantity.value++
}
</script>
<template>
<button @click="incrementQuantity">
Add item
</button>
<p>Total: {{ total }}</p>
</template>
It uses computed to automatically derive a value from other reactive values.
Reactderived value
import { useState } from 'react'
function CartTotal() {
const price = 8
const [quantity, setQuantity] = useState(1)
const total = price * quantity
function incrementQuantity() {
setQuantity(quantity + 1)
}
return (
<>
<button onClick={incrementQuantity}>
Add item
</button>
<p>Total: {total}</p>
</>
)
}
It calculates the total directly during render from the available state instead of storing it as extra state.
Angularcomputed
import { Component, computed, signal } from '@angular/core'
@Component({
selector: 'app-cart-total',
standalone: true,
template: `
<button (click)="incrementQuantity()">
Add item
</button>
<p>Total: {{ total() }}</p>
`,
})
export class CartTotalComponent {
price = signal(8)
quantity = signal(1)
total = computed(() => this.price() * this.quantity())
incrementQuantity() {
this.quantity.update((value) => value + 1)
}
}
It uses computed to derive a value from other signals without turning it into separate state.
