Vue.js Developer interview question · Most asked

ref or reactive: what is the difference, and when do you use each?

Summary

ref() wraps any value (primitives included) in an object with a .value property; reactive() makes an object deeply reactive through a Proxy and only works with objects. The Vue docs recommend ref() as the primary API because reactive() has limitations.

Longer Answer

reactive() limitations: it cannot hold primitives; replacing the whole object breaks the reactive connection (state = reactive({...}) again loses tracking for existing references); and destructuring or passing a property to a function loses reactivity (const { count } = state is a plain number). ref avoids these: you can reassign .value freely. Refs are automatically unwrapped in templates and when nested inside reactive objects (but not inside arrays or Maps).

toRefs(state) converts a reactive object's properties into refs so destructuring keeps reactivity, a common pattern when returning state from composables.

Code Example

import { ref, reactive, toRefs } from "vue";

const count = ref(0);
count.value++;            // template: {{ count }} (auto-unwrapped)

const state = reactive({ user: null, loading: false });
const { loading } = toRefs(state);  // stays reactive

Key Points

  • ref: any value, .value.
  • reactive: objects only, Proxy-based.
  • Destructuring reactive loses reactivity.
  • Docs recommend ref by default; toRefs for destructuring.

More most-asked Vue.js Developer questions

← All Vue.js Developer questions