#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 25 of 37medium

What are toRefs and toRef in Vue?

Maintaining reactivity when destructuring.

What You'll Learn

  • The destructuring problem
  • toRefs usage
  • toRef usage

The Problem

code.jsJavaScript
const state = reactive({ count: 0, name: 'Vue' })

// Loses reactivity!
const { count, name } = state
count++ // Won't update state.count

toRefs Solution

code.jsJavaScript
import { reactive, toRefs } from 'vue'

const state = reactive({ count: 0, name: 'Vue' })

// Maintains reactivity
const { count, name } = toRefs(state)
count.value++ // Updates state.count

toRef for Single Property

code.jsJavaScript
import { reactive, toRef } from 'vue'

const state = reactive({ count: 0 })

// Create ref for single property
const countRef = toRef(state, 'count')
countRef.value++ // Updates state.count

// With default value
const missing = toRef(state, 'missing', 0)

Common Pattern with Composables

code.jsJavaScript
// composable returns reactive object
function useFeature() {
  const state = reactive({ ... })
  return toRefs(state)
}

// Usage - can destructure safely
const { count, name } = useFeature()