
Vue 3 introduced the Composition API, giving us powerful tools (ref
, reactive
, computed
, watch
, etc.) to manage state in a more flexible way. At the core of this is reactivity: Vue automatically tracks changes to data and updates the DOM.
Two of the most important APIs are:
-
ref()
→ makes a single value reactive. -
reactive()
→ makes an object (or array) reactive.
Let’s dive in.
1. ref()
: Reactive Primitive Values
ref
is used when you want to make a single value reactive (string, number, boolean, or even objects if you prefer).
2. reactive()
: Reactive Objects
When you have an object or array with multiple properties, reactive
is often more convenient.
3. ref()
with Objects
You can wrap objects with ref
. Vue will still make them reactive, but you’ll need .value
to access the object.
4. ref
vs reactive
– When to Use?
-
Use
ref
for primitives (numbers, strings, booleans). -
Use
reactive
for objects and arrays with many properties. -
Use
ref
for objects if you need to reassign/replace them entirely.
// Good: reassigning entire object const settings = ref({ darkMode: false }) settings.value = { darkMode: true } // Works // With reactive, reassigning breaks reactivity: const prefs = reactive({ darkMode: false }) prefs = { darkMode: true } // ❌ Not reactive anymore
As you be aware that reassigning entire object with reactive breaks reactivity, you can use ref() or if using reactive try mutating specific object keys like so:
const prefs = reactive({ theme: { darkMode: false } }) prefs.theme = { darkMode: true }
5. Watching Changes
Sometimes you need to run code when a reactive value changes. With vue 3 watch
.
7. Common Pitfalls ⚠️
- Forgetting
.value