Introduction
VuReact, a powerful tool for bridging Vue and React ecosystems, offers seamless conversion of Vue 3's reactive APIs into React code. This article explores how VuReact handles the transformation of Vue's ref() and shallowRef() into React's useVRef() and useShallowVRef().
Understanding Vue ref() to React useVRef()
In Vue 3, ref() is a cornerstone of reactivity, frequently used in everyday coding. Let's examine a basic example:
Vue Example
<script setup>
import { ref } from 'vue';
// Primitive reactive state
const count = ref(0);
</script>
Compiled React Version
import { useVRef } from '@vureact/runtime-core';
// Mirrors Vue ref semantics in React
const count = useVRef(0);
VuReact's useVRef mirrors Vue's ref(), preserving its reactive nature and ensuring smooth updates and view re-rendering in React.
TypeScript Support Maintained
VuReact ensures TypeScript annotations are retained, preserving type safety and providing valuable editor hints. Here's how it looks in Vue and React:
Vue Example with TypeScript
<script lang="ts" setup>
const title = ref<string>('');
const isLoading = ref<boolean>(false);
const userList = ref<Array<{ id: number; name: string }>>([]);
const config = ref<Record<string, any>>({ theme: 'dark' });
</script>
React Equivalent
const title = useVRef<string>('');
const isLoading = useVRef<boolean>(false);
const userList = useVRef<Array<{ id: number; name: string }>>([]);
const config = useVRef<Record<string, any>>({ theme: 'dark' });
The conversion requires no manual adaptation, ensuring the React code is as type-safe as the Vue original.
Vue shallowRef() to React useShallowVRef()
Vue 3's shallowRef() is ideal for tracking top-level changes without deep reactivity. Here's how it's converted to React:
Vue Example
<script setup>
import { shallowRef } from 'vue';
// Tracks only top-level changes
const count = shallowRef({ a: { b: 1, c: { d: 2 } } });
</script>
Compiled React Version
import { useShallowVRef } from '@vureact/runtime-core';
// Maintains shallow reactivity
const count = useShallowVRef({ a: { b: 1, c: { d: 2 } } });
VuReact's useShallowVRef adapts shallowRef for React, triggering updates only for top-level reference changes, aligning with React's update model and benefiting performance, especially in complex object scenarios.