Skip to content

Conversation

@pauloappbr
Copy link

@pauloappbr pauloappbr commented Dec 26, 2025

Note: Although this issue was originally discussed in the context of Vue 2, the limitation is inherent to the Composition API's watch implementation, which is best addressed here in the core repository for Vue 3.5+.

What this PR does

This PR introduces a new equals option to the watch and watchEffect APIs. This allows developers to provide a custom equality function to determine if the watcher's callback and its associated cleanup should be triggered.

Why we need it

Currently, onCleanup is invoked by the scheduler whenever the source reference changes, regardless of whether the semantic data is identical. In scenarios involving abortable side-effects (e.g., using AbortController.abort()), the cleanup runs before the callback comparison logic can intervene.

This makes it impossible to prevent unnecessary side-effect interruptions when using deep: true or watching objects that are frequently recreated but semantically equivalent. By providing a native equals option, we can short-circuit the effect lifecycle before the cleanup is even called.

Technical Implementation

@vue/reactivity: Modified the internal job in watch.ts to evaluate the options.equals function if provided. If the function returns true, the cleanup() and the callback are skipped.

@vue/runtime-core: Updated WatchOptions interface to expose the equals property to the end-user API.

Precedence: The equals option takes precedence over the default hasChanged check, ensuring full control over the trigger conditions.

Example Usage


watch(
  () => props.data,
  (newVal, oldVal, onCleanup) => {
    const controller = new AbortController()
    onCleanup(() => controller.abort())
    fetchData(newVal, controller.signal)
  },
  { 
    deep: true,
    equals: (a, b) => JSON.stringify(a) === JSON.stringify(b) 
  }
)

Related Issue

Relates to vuejs/vue#13242 (Forward-port of the requested feature to Vue 3 Core)

Summary by CodeRabbit

  • New Features

    • Added an optional equals function for watchers to provide custom equality checks that determine when callbacks run.
  • Behavior

    • Watcher cleanup and callback invocation now honor equals logic so semantically equal values can skip triggering; equals takes precedence over deep/force-trigger behavior.
  • Tests

    • Added tests validating cleanup and callback behavior when custom equality comparators are used.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 26, 2025

📝 Walkthrough

Walkthrough

Added an equals option to watcher APIs and updated change-detection to use an areEqual/isChanged/shouldTrigger flow that lets a custom equality function control whether cleanup and callbacks run.

Changes

Cohort / File(s) Summary
Core watch implementation
packages/reactivity/src/watch.ts
Adds equals-aware change detection: introduces local areEqual helper, computes isChanged (handles multi-source), and derives shouldTrigger so equals can gate cleanup and callback invocation; wraps equals calls with WATCH_CALLBACK error routing.
Runtime API types & integration
packages/runtime-core/src/apiWatch.ts
Adds equals?: (a: any, b: any) => boolean to WatchOptions and wires the option into watcher trigger logic.
Tests
packages/runtime-core/__tests__/apiWatch.spec.ts
Adds tests asserting cleanup behavior when callback early-skips cleanup and that a custom equals prevents cleanup and callback when values are semantically equal.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

scope: reactivity

Suggested reviewers

  • edison1105

Poem

🐰 I nibble at change-detect seams,

I hop through equals and silent streams.
Cleanups linger until truth is found,
Callbacks bloom when changes sound.
A tiny rabbit, code unbound.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding an 'equals' option to the watch API for custom equality checks, which is the core feature implemented across all modified files.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 521ed12 and f55a814.

📒 Files selected for processing (1)
  • packages/reactivity/src/watch.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/reactivity/src/watch.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/runtime-core/__tests__/apiWatch.spec.ts (1)

2064-2091: Add assertions after the second value assignment.

The test demonstrates the workaround for the issue, but it's missing final assertions after line 2091 to verify that cleanupCount and effectCount remain unchanged when the semantically identical value is assigned again.

🔎 Suggested assertions
   state.value = { id: 2 }
   await nextTick()
+  // Should not trigger because values are semantically equal
+  expect(effectCount).toBe(1)
+  expect(cleanupCount).toBe(0)
 })
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c68bebf and e08c83b.

📒 Files selected for processing (3)
  • packages/reactivity/src/watch.ts
  • packages/runtime-core/__tests__/apiWatch.spec.ts
  • packages/runtime-core/src/apiWatch.ts
🧰 Additional context used
🧬 Code graph analysis (1)
packages/runtime-core/__tests__/apiWatch.spec.ts (4)
packages/reactivity/src/ref.ts (1)
  • ref (61-63)
packages/reactivity/src/watch.ts (1)
  • watch (121-337)
packages/runtime-core/src/apiWatch.ts (1)
  • watch (132-145)
packages/runtime-core/src/scheduler.ts (1)
  • nextTick (61-67)
🔇 Additional comments (3)
packages/runtime-core/src/apiWatch.ts (1)

53-53: LGTM! Type definition is clear and consistent.

The equals option is properly typed as optional and follows Vue's pattern for watch options. The any types are pragmatic for a general-purpose equality comparator, though they sacrifice type safety.

packages/runtime-core/__tests__/apiWatch.spec.ts (1)

2092-2121: LGTM! Test properly validates the equals option functionality.

The test correctly verifies that when a custom equals function returns true, both the callback and cleanup are suppressed. The test cases cover the essential scenarios: initial change triggering the callback, and subsequent semantically-equal assignments being skipped.

packages/reactivity/src/watch.ts (1)

53-53: LGTM! Consistent with the runtime-core API definition.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/reactivity/src/watch.ts (1)

244-257: Consider type-safe generics for the equals function signature.

The current signature equals?: (a: any, b: any) => boolean loses type information about the watched values. While consistent with existing patterns in the codebase, consider enhancing type safety in a future iteration by making WatchOptions generic over the source type(s) so equals receives properly typed parameters.

This would provide better IntelliSense and catch type mismatches at compile time.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e08c83b and 1dc011c.

📒 Files selected for processing (3)
  • packages/reactivity/src/watch.ts
  • packages/runtime-core/__tests__/apiWatch.spec.ts
  • packages/runtime-core/src/apiWatch.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/runtime-core/tests/apiWatch.spec.ts
🧰 Additional context used
🧬 Code graph analysis (1)
packages/reactivity/src/watch.ts (1)
packages/shared/src/general.ts (1)
  • hasChanged (143-144)
🔇 Additional comments (3)
packages/runtime-core/src/apiWatch.ts (1)

53-58: LGTM! Clear documentation of the new equals option.

The JSDoc accurately describes the behavior and precedence of the equals option. The documentation correctly states that equals takes precedence over the default equality check, deep, and forceTrigger, which aligns with the implementation in watch.ts.

packages/reactivity/src/watch.ts (2)

53-53: LGTM! Type definition matches the public API.

The equals option is correctly added to the WatchOptions interface, maintaining consistency with the definition in runtime-core/src/apiWatch.ts.


253-254: Good: Inline comment clarifies equals precedence.

The inline comment addresses the previous review feedback by clearly documenting that equals bypasses deep and forceTrigger logic when provided. This helps developers understand the precedence behavior.

Comment on lines 244 to 257
const isChanged = isMultiSource
? (newValue as any[]).some((v, i) =>
options.equals
? !options.equals(v, oldValue[i])
: hasChanged(v, oldValue[i]),
)
: options.equals
? !options.equals(newValue, oldValue)
: hasChanged(newValue, oldValue)
// If equals is provided, it fully controls the trigger decision,
// bypassing deep and forceTrigger logic.
const shouldTrigger = options.equals
? isChanged
: deep || forceTrigger || isChanged
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add error handling around user-provided equals function calls.

If the user-provided equals function throws an exception (e.g., due to accessing properties on null/undefined, or internal logic errors), the entire watcher job will fail, potentially breaking reactive updates and leaving the component in an inconsistent state.

Wrap the equals invocations in try-catch blocks and handle errors gracefully, similar to how other user callbacks are handled via the call helper throughout this codebase.

🔎 Example approach for error handling

Consider wrapping equals calls:

 const isChanged = isMultiSource
   ? (newValue as any[]).some((v, i) =>
       options.equals
-        ? !options.equals(v, oldValue[i])
+        ? !safeEquals(options.equals, v, oldValue[i])
         : hasChanged(v, oldValue[i]),
     )
   : options.equals
-    ? !options.equals(newValue, oldValue)
+    ? !safeEquals(options.equals, newValue, oldValue)
     : hasChanged(newValue, oldValue)

Where safeEquals is a helper that wraps the call in try-catch and uses the call helper for error handling, or falls back to hasChanged on error.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/reactivity/src/watch.ts around lines 244 to 257, user-supplied
equals calls are invoked directly and can throw, which would crash the watcher;
wrap every equals invocation (both in the multi-source some(...) comparator and
the single-source branch) in a small try-catch wrapper (or create a safeEquals
helper) that calls the equals using the existing call helper for consistent
error handling, and on exception fall back to using hasChanged (or treat as
changed) so the watcher continues to function; ensure the computed isChanged and
shouldTrigger use the safe result and preserve existing deep/forceTrigger
behavior.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1dc011c and 521ed12.

📒 Files selected for processing (1)
  • packages/reactivity/src/watch.ts
🔇 Additional comments (3)
packages/reactivity/src/watch.ts (3)

53-53: LGTM!

Clean API addition that follows the existing optional property pattern in WatchOptions.


259-267: LGTM!

The isChanged calculation correctly handles both single and multi-source watchers. The shouldTrigger logic appropriately lets custom equals take full control of the trigger decision when provided, which aligns with user expectations when they explicitly opt into custom equality semantics. The inline comment clearly documents this design choice.


268-268: LGTM!

The conditional correctly uses shouldTrigger to gate both cleanup and callback invocation, ensuring that semantically equal values (per custom equals) skip unnecessary side-effects.

@edison1105 edison1105 moved this to In Progress in Next Minor Dec 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

2 participants