Back
VueHardNew

What is `toRef` and `toRefs`, and when would you use them?

Preserving reactivity when destructuring reactive objects

Ideal Answer

Destructuring properties from a reactive() object loses reactivity, since you end up with a plain disconnected value. toRefs converts every property of a reactive object into an individual ref linked back to the source, and toRef does this for a single property.

JavaScript
import { reactive, toRefs } from 'vue'

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

count.value++ // updates state.count too

This is especially common when returning values from a composable, so consumers can destructure the returned object without losing reactivity.