news May 21, 2026 · 63 views · 2 min read

Transforming Vue watch() into React with VuReact

Explore how VuReact seamlessly converts Vue 3's watch() API into React's useWatch(), maintaining functionality and simplifying code maintenance.

Transforming Vue watch() into React with VuReact

VuReact offers a compelling solution for developers looking to convert Vue 3 code into React without losing functionality. This article focuses on how VuReact transforms Vue's watch() API into a React-compatible format.

Understanding the Basics

Vue's watch() function is pivotal for monitoring reactive data and executing side effects when changes occur. VuReact translates this into useWatch(), enabling automated dependency tracking and reducing manual intervention.

Vue to React Conversion

Consider a simple example:

Vue

<script setup>
import { ref, watch } from 'vue';

const userId = ref(1);

watch(
  userId,
  async (newId, oldId, onCleanup) => {
    let cancelled = false;

    onCleanup(() => {
      cancelled = true;
    });

    const data = await fetchUser(newId);
    if (!cancelled) {
      userData.value = data;
    }
  },
  { immediate: true },
);
</script>

Compiled React

import { useVRef, useWatch } from '@vureact/runtime-core';

const userId = useVRef(1);

useWatch(
  userId,
  async (newId, oldId, onCleanup) => {
    let cancelled = false;

    onCleanup(() => {
      cancelled = true;
    });

    const data = await fetchUser(newId);
    if (!cancelled) {
      setUserData(data);
    }
  },
  { immediate: true },
);

Here, watch() is seamlessly mapped to useWatch(), retaining its core features like callbacks, cleanup operations, and immediate execution.

Handling Complex Scenarios

VuReact also excels with deep and multi-source watching scenarios.

Deep Watching Example

Vue

<script setup>
import { reactive, watch } from 'vue';

const state = reactive({
  info: { name: 'VuReact', version: '1.0' },
  count: 0,
});

watch(
  () => state.info,
  (newInfo) => {
    console.log('nested change:', newInfo.name);
  },
  { deep: true },
);

watch([state.count, () => state.info.name], ([newCount, newName]) => {
  console.log('count:', newCount, 'name:', newName);
});
</script>

Compiled React

import { useReactive, useWatch } from '@vureact/runtime-core';

const state = useReactive({
  info: { name: 'VuReact', version: '1.0' },
  count: 0,
});

useWatch(
  () => state.info,
  (newInfo) => {
    console.log('nested change:', newInfo.name);
  },
  { deep: true },
);

useWatch([state.count, () => state.info.name], ([newCount, newName]) => {
  console.log('count:', newCount, 'name:', newName);
});

VuReact efficiently handles the complexity of deep watching and multiple dependencies, automating the tracking process and ensuring expected behavior without manual adjustments.

Conclusion

Discussion

0 Comments

Leave a Comment

Comments are moderated and will appear after approval.