🎓 A1Learner
🔍
0 of 50 lessons completed

ref vs reactive

ref and reactive both make values reactive in Vue. They fit different kinds of values, so each has its own place.

One value with ref

The count starts at 0.

import { ref } from 'vue'
const count = ref(0)

A group with reactive

The count starts at 0.

import { reactive } from 'vue'
const state = reactive({ count: 0 })

Change each one

The ref count becomes 2 and the reactive count becomes 3.

import { ref, reactive } from 'vue'
const count = ref(0)
const state = reactive({ count: 0 })
count.value = 2
state.count = 3

ref holds a string

The name is Ana.

import { ref } from 'vue'
const name = ref('Ana')

Example

<script setup>
import { ref, reactive } from 'vue'
const count = ref(0)
const state = reactive({ count: 0 })
</script>
<template>
  <div>
    <p>ref count: {{ count }}</p>
    <p>reactive count: {{ state.count }}</p>
  </div>
</template>

Key points

  • ref holds one value, like a number or a string.
  • reactive holds an object with named properties.
  • ref needs .value in script code, and reactive does not.
  • In the template, both work with plain names.
  • A ref can hold an object too, but reactive fits objects better.

In this example, the script makes a ref count and a reactive state. Both counts start at 0. The template shows each count on its own line. The page first shows ref count: 0 and reactive count: 0. If the ref count becomes 1 and the state count becomes 2, the page shows 1 and 2.

Note

Pick ref for one value and reactive for a group of values.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which one fits a single number?