JAVASCRIPT

Managing Complex State with `reactive` and `toRefs`

Learn how to create deeply reactive objects using `reactive` and safely destructure them in Vue 3's Composition API with `toRefs` to maintain reactivity.

// MyComponent.vue
<script setup>
import { reactive, toRefs } from 'vue';

const user = reactive({
  id: 1,
  name: 'Alice',
  email: '[email protected]',
  settings: {
    theme: 'dark',
    notifications: true
  }
});

// To destructure reactive properties while maintaining reactivity,
// use toRefs. Otherwise, destructuring directly would lose reactivity.
const { name, email, settings } = toRefs(user);

const updateName = () => {
  name.value = 'Alicia'; // Access via .value when destructured with toRefs
  console.log('User name updated to:', user.name);
};

const toggleNotifications = () => {
  user.settings.notifications = !user.settings.notifications; // Direct access to nested reactive properties
  console.log('Notifications status:', user.settings.notifications);
};
</script>

<template>
  <div>
    <h1>User Profile</h1>
    <p>Name: {{ name }}</p>
    <p>Email: {{ email }}</p>
    <p>Theme: {{ settings.theme }}</p>
    <p>Notifications: {{ settings.notifications ? 'On' : 'Off' }}</p>
    <button @click="updateName">Update Name</button>
    <button @click="toggleNotifications">Toggle Notifications</button>
  </div>
</template>
How it works: This snippet demonstrates how to use Vue 3's `reactive` API to create a deeply reactive object, ideal for complex state. It also showcases `toRefs`, which is crucial when destructuring properties from a `reactive` object. Destructuring without `toRefs` would break reactivity for those properties, making `toRefs` essential for easily using reactive properties in your template or other functions while keeping their reactivity intact.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs