Skip to content

Instantly share code, notes, and snippets.

@Bazsmagister
Created September 20, 2023 18:12
Show Gist options
  • Save Bazsmagister/3ba7f2290502cf29fdbf8579aecb970e to your computer and use it in GitHub Desktop.
Save Bazsmagister/3ba7f2290502cf29fdbf8579aecb970e to your computer and use it in GitHub Desktop.
ref() vs reactive() in Vue3
In Vue 3, both ref() and reactive() are used for creating reactive data, but they have some differences in how they work and what kind of data they are best suited for.
ref():
Atomic Values: ref() is primarily used for creating reactive references to atomic values, such as numbers, strings, booleans, or any other single non-object value.
Unwrapping: When you access a value created with ref(), you need to explicitly use the .value property to access the underlying value. This is because ref() wraps the value in an object to make it reactive.
Use Cases: Use ref() for simple, individual values that need reactivity. For example, you might use ref() for a numeric counter, a string message, or a boolean flag.
Reactive():
Objects: reactive() is used to create a fully reactive object. It takes an object as an argument and recursively makes all of its properties reactive.
Automatic Unwrapping: With reactive()-created objects, you don't need to use .value to access properties; you can access them directly like normal object properties.
Use Cases: Use reactive() when you need to manage complex data structures like configuration objects, form data, or state objects with multiple properties.
In summary, ref() is used for individual, atomic values and requires explicit .value access, while reactive() is used for creating reactive objects with multiple properties, and you can access these properties directly. The choice between them depends on the kind of data you are working with in your Vue 3 application.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment