← Back to Vue.js Course | Chapter 3: Reactivity | Lesson 4 of 7

reactive()

reactive makes a whole object deeply reactive so that changing its properties updates the view.

In this page:

  1. reactive()
Syntax
markup
import { reactive } from 'vue';
const state = reactive({ property: value });
state.property = new_value;

reactive()

reactive wraps an object in a Proxy that tracks reads and writes to every property, including nested ones. You access properties directly without .value.

Do not replace the whole object or destructure it, because either loses reactivity; use toRefs when destructuring.

Note: reactive only works with objects, not primitive values like numbers or strings.

Example: reactive()

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <p>{{ state.name }} has {{ state.items.length }} items</p>
  <button @click="add">Add</button>
</div>
<script>
  Vue.createApp({
    setup() {
      const state = Vue.reactive({ name: "Cart", items: ["pen"] });
      const add = () => state.items.push("ink");
      return { state, add };
    },
  }).mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: Cart has 2 itemsAdd
console: Cart has 2 items
-->
Live Example
Related Topics
Common Mistakes
  1. Reassigning the whole reactive object
  2. Destructuring properties and losing reactivity
  3. Using reactive for primitives
Chapter Summary
  • reactive proxies an object deeply
  • No .value needed
  • Do not replace or destructure carelessly
  • Use toRefs to destructure
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.