Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon can you provide examples where ref() and reactive() are used together effectively


can you provide examples where ref() and reactive() are used together effectively


Here are some examples where `ref()` and `reactive()` are used together effectively:

Example 1: Using `ref()` for Primitive Values and `reactive()` for Complex Objects

javascript
import { ref, reactive } from 'vue';

const count = ref(0);
const user = reactive({
  name: 'Michael Scott',
  address: {
    street: '123 Main St',
    city: 'Scranton',
    state: 'PA',
    zip: '12345'
  }
});

// Accessing primitive value
console.log(count.value); // logs 0

// Accessing reactive object
console.log(user.name); // logs Michael Scott
console.log(user.address.street); // logs 123 Main St

Example 2: Using `ref()` for State Management and `reactive()` for Validation

javascript
import { ref, reactive } from 'vue';
import { validate } from 'vuelidate';

const state = reactive({
  name: '',
  email: ''
});

const rules = reactive({
  name: { required: true },
  email: { required: true, email: true }
});

async function submit() {
  const result = await validate(state, rules);
  if (result.$invalid) {
    console.log('Invalid form');
  } else {
    console.log('Form is valid');
  }
}

// Using ref for state management
const loading = ref(false);

async function fetchData() {
  loading.value = true;
  const response = await apiCall();
  loading.value = false;
  // Process response
}

Example 3: Using `ref()` for Nested Objects and `reactive()` for Deep Reactivity

javascript
import { ref, reactive } from 'vue';

const nestedObject = ref({
  a: {
    b: {
      c: 'Hello'
    }
  }
});

const deepReactive = reactive({
  nestedObject: nestedObject
});

// Accessing nested object
console.log(nestedObject.value.a.b.c); // logs "Hello"

// Accessing reactive object
console.log(deepReactive.nestedObject.a.b.c); // logs "Hello"

These examples demonstrate how `ref()` and `reactive()` can be used together effectively to manage different types of data and achieve specific goals in Vue applications.

Citations:
[1] https://fadamakis.com/ref-vs-reactive-pick-one-kill-the-other-95089f942327?gi=c6cc655c6594
[2] https://blog.logrocket.com/reactivity-vue-3-composition-api-ref-reactive/
[3] https://laracasts.com/discuss/channels/vue/is-there-any-penalty-using-reactive-rather-than-ref
[4] https://www.reddit.com/r/vuejs/comments/1192u4q/ref_vs_reactive_which_is_best/
[5] https://michaelnthiessen.com/ref-vs-reactive