Hack Frontend Community

How Does Reactivity Work in Vue.js?

What is Reactivity?

Reactivity is when data changes, Vue automatically updates interface elements associated with them. This is achieved through dependency tracking system.

How Does It Work?

  • Vue tracks changes in reactive variables.
  • When value changes, components depending on it automatically re-render.
  • ref() and reactive() are used for working with reactive data.

ref()

ref() is used to create reactive values. It's suitable for working with primitives (numbers, strings, booleans) and objects.

ref() Usage Example

<script setup>
import { ref } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};
</script>
  • count = ref(0); — create reactive value count equal to 0.
  • count.value++ — since ref() requires access through .value, we increment count value this way.
  • When count.value changes, Vue automatically updates template (template).

reactive()

reactive() is used to create reactive objects and arrays.

reactive() Usage Example

<script setup>
import { reactive } from 'vue';

const state = reactive({ count: 0 });

const increment = () => {
  state.count++;
};
</script>
  • state = reactive({ count: 0 }); — create object state with reactive property count.
  • state.count++ — increment count value without .value, since reactive() works directly with objects.
  • Vue automatically tracks changes and updates interface.

Difference Between ref() and reactive()

Criterionref()reactive()
Primitive supportYesNo
Object supportYesYes
Value accessThrough .valueDirect access
Deep reactivityYesYes
Structure changeEasy (can assign new value)Cannot (structure is fixed)

When to Use?

  • ref() — if you need to work with primitives.
  • reactive() — if you need to create reactive object.
  • Combination — can use ref() inside reactive(), if you need to store primitive values in reactive object.

Combined Approach Example:

<script setup>
import { reactive, ref } from 'vue';

const state = reactive({
  count: ref(0)
});

const increment = () => {
  state.count.value++;
};
</script>
  • state = reactive({ count: ref(0) }); — object state contains reactive value count created via ref().
  • state.count.value++ — access to ref() inside reactive() requires .value.
  • This approach is convenient if part of data in object should be primitives with ability to assign new value.

Summary

Vue.js provides two powerful mechanisms for working with reactive data:

  • ref() — for primitive values and objects with access through .value.
  • reactive() — for working with objects and arrays without .value.

Both methods can be combined depending on project requirements. Choice depends on data structure and convenience of working with them.