VuReact is a tool that compiles Vue 3 code into standard, maintainable React code. This time, the focus is on two frequently used Vue APIs: toRef() and toRefs().
If you use them in Vue, what does the resulting React code look like after VuReact compilation?
A Quick Note Before the Examples
To avoid noisy examples, this article follows two small conventions:
- All Vue and React snippets show only the core logic, with full component wrappers and unrelated setup omitted.
- The discussion assumes you are already familiar with the API shape and behavior of Vue 3
toRefandtoRefs.
Compilation Mapping
Vue toRef() -> React useToVRef()
toRef() is Vue 3's API for turning a single property on a reactive object into a ref. It is especially useful when you want to destructure state without losing reactivity.
VuReact compiles this into useToVRef().
- Vue
<script setup>
import { reactive, toRef } from 'vue';
const state = reactive({
count: 1,
user: { name: 'Gemini' },
});
const countRef = toRef(state, 'count');
</script>
- Compiled React
import { useReactive, useToVRef } from '@vureact/runtime-core';
const state = useReactive({
count: 1,
user: { name: 'Gemini' },
});
const countRef = useToVRef(state, 'count');
As the example shows, Vue toRef() maps directly to useToVRef().
VuReact's useToVRef is the runtime adapter for toRef(). The extracted ref remains linked to the original source, so countRef.value stays in sync with state.count in both directions.
Vue toRefs() -> React useToVRefs()
toRefs() converts every property on a reactive object into a corresponding ref. This is a common way to destructure state safely without breaking reactivity.
VuReact compiles that pattern into useToVRefs().
- Vue
<script setup>
import { reactive, toRefs } from 'vue';
const state = reactive({
foo: 1,
bar: 'Hello',
});
const { foo, bar } = toRefs(state);
</script>
- Compiled React
import { useReactive, useToVRefs } from '@vureact/runtime-core';
const state = useReactive({
foo: 1,
bar: 'Hello',
});
const { foo, bar } = useToVRefs(state);
VuReact's useToVRefs is the runtime adapter for toRefs(). The destructured foo and bar are still ref objects, which means you can read and update them through .value while keeping them synchronized with the original reactive object.
Top comments (0)