Skip to content

fix(reactivity): should not recompute if computed does not track reactive data #12341

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 1, 2025

Conversation

edison1105
Copy link
Member

@edison1105 edison1105 commented Nov 7, 2024

revert #11931 re-fix #11929
close #12337

Summary by CodeRabbit

  • New Features

    • Improved computed property performance by preventing unnecessary recomputation when no reactive dependencies are tracked.
  • Tests

    • Added a test to confirm that computed properties do not recompute if their getter does not access reactive data.

Copy link

github-actions bot commented Nov 7, 2024

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB (+3 B) 38.2 kB (+4 B) 34.4 kB (+41 B)
vue.global.prod.js 159 kB (+3 B) 58.4 kB (+4 B) 51.9 kB (+14 B)

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.5 kB (+3 B) 18.2 kB (+2 B) 16.6 kB (+9 B)
createApp 54.5 kB (+3 B) 21.2 kB 19.4 kB (-6 B)
createSSRApp 58.7 kB (+3 B) 22.9 kB (+2 B) 20.9 kB (-4 B)
defineCustomElement 59.3 kB (+3 B) 22.8 kB 20.8 kB (+6 B)
overall 68.6 kB (+3 B) 26.4 kB (-1 B) 24 kB (+2 B)

Copy link

pkg-pr-new bot commented Nov 7, 2024

Open in StackBlitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@12341

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@12341

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@12341

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@12341

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@12341

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@12341

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@12341

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@12341

@vue/shared

npm i https://pkg.pr.new/@vue/shared@12341

vue

npm i https://pkg.pr.new/vue@12341

@vue/compat

npm i https://pkg.pr.new/@vue/compat@12341

commit: 7eaa8fd

@linzhe141
Copy link
Contributor

Maybe this modification will be simpler

export function triggerRef(ref: Ref): void {
  // ref may be an instance of ObjectRefImpl
  if ((ref as unknown as RefImpl).dep) {
    // add
    if ((ref as unknown as RefImpl).dep.computed) {
      refreshComputed((ref as unknown as RefImpl).dep.computed!)
    }
    ...
  }
}

@edison1105 edison1105 requested a review from jh-leong November 7, 2024 03:59
@edison1105 edison1105 changed the title fix(reactivity): force trigger computed fix(reactivity): should not recompute if computed does not track reactive data Nov 7, 2024
@edison1105 edison1105 added ready to merge The PR is ready to be merged. scope: reactivity and removed ready to merge The PR is ready to be merged. labels Nov 7, 2024
@edison1105 edison1105 marked this pull request as draft November 7, 2024 07:33
@edison1105 edison1105 marked this pull request as ready for review November 7, 2024 08:01
@vuejs vuejs deleted a comment from vue-bot Nov 7, 2024
@vuejs vuejs deleted a comment from vue-bot Nov 7, 2024
@vuejs vuejs deleted a comment from vue-bot Nov 7, 2024
@edison1105 edison1105 added the ready to merge The PR is ready to be merged. label Nov 7, 2024
@edison1105 edison1105 added the 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. label Jan 7, 2025
Copy link

coderabbitai bot commented May 1, 2025

Walkthrough

The changes introduce a new EVALUATED flag to the EffectFlags enum and update the logic in the computed property re-evaluation process to optimize when recomputation occurs. Specifically, computed properties that do not track any reactive dependencies and have already been evaluated will no longer recompute unnecessarily. A unit test is added to verify that a computed property without reactive dependencies does not recompute even when unrelated reactive state changes. These updates address issues where computed properties were recomputed more often than intended.

Changes

File(s) Change Summary
packages/reactivity/src/effect.ts Added EVALUATED to EffectFlags enum; updated refreshComputed logic to optimize recomputation.
packages/reactivity/__tests__/computed.spec.ts Added test to ensure computed without reactive dependencies does not recompute on unrelated changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Computed
    participant ReactiveRef

    User->>Computed: Access computed.value
    Computed->>Computed: Evaluate getter (no reactive deps)
    User->>ReactiveRef: Change ref.value
    User->>Computed: Access computed.value again
    Computed-->>User: Return cached value (no recomputation)
Loading

Assessment against linked issues

Objective Addressed Explanation
Prevent computed from recomputing if it does not track any reactive data (#12337)
Ensure computed callback is invoked as expected when using triggerRef (#11929)

Poem

A tweak in the wires, a flag in the code,
Computed now rests when it carries no load.
No more will it run when the world changes hue,
If nothing is watched, it has nothing to do!
With tests in the garden, the logic is sound—
The bunnies rejoice as the cycles slow down.
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 0

🧹 Nitpick comments (3)
packages/reactivity/src/effect.ts (2)

41-53: Add succinct JSDoc for the new EVALUATED flag

The semantics of the new bit are only implied by later usage. A short inline comment (similar to the other flags) will make its purpose self-explanatory to future maintainers.

   PAUSED = 1 << 6,
+  /**
+   * Computed has executed at least once and produced a value.
+   * Used to skip redundant evaluations when it tracks no deps.
+   */
   EVALUATED = 1 << 7,

385-394: Early-return condition is correct but hard to read – consider extracting helpers

The triple-negated expression:

(!computed.deps && !(computed as any)._dirty) || !isDirty(computed)

is cognitively heavy and mixes two separate ideas (“no deps” vs “deps unchanged”).
Creating small predicates such as hasNoDeps(computed) and depsUnchanged(computed) (or at least splitting the check across two if blocks) would improve clarity without affecting perf.

packages/reactivity/__tests__/computed.spec.ts (1)

1015-1024: async keyword is unnecessary in this test

The test body contains no await; marking it async only masks accidental un-awaited promises and slightly slows the runner.

-test('should not recompute if computed does not track reactive data', async () => {
+test('should not recompute if computed does not track reactive data', () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b848cb and 7eaa8fd.

📒 Files selected for processing (2)
  • packages/reactivity/__tests__/computed.spec.ts (1 hunks)
  • packages/reactivity/src/effect.ts (3 hunks)
🔇 Additional comments (1)
packages/reactivity/src/effect.ts (1)

394-418: RUNNING flag now set after the early return – verify re-entrancy in edge cases

Moving computed.flags |= RUNNING below the new guard avoids polluting the stack for short-circuited calls, 👍.
However, if a getter with side-effects clears its own DIRTY flag inside prepareDeps, there’s a theoretical chance of re-entrancy before RUNNING is set (because external code could synchronously access the same computed in the getter).

That situation is rare but not impossible in user-space (e.g. self-mutating computeds).
Consider adding a regression test or, at minimum, a comment explaining why re-entrancy before RUNNING is impossible with the current control flow.

@vuejs vuejs deleted a comment from edison1105 May 1, 2025
@yyx990803
Copy link
Member

/ecosystem-ci run

@vuejs vuejs deleted a comment from yyx990803 May 1, 2025
@vue-bot
Copy link
Contributor

vue-bot commented May 1, 2025

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools success success
pinia success success
primevue success success
quasar success success
nuxt success success
radix-vue success success
vue-i18n success success
vant success success
router success success
vite-plugin-vue success success
vitepress success success
test-utils success success
vuetify success success
vueuse success success
vue-macros success success
vue-simple-compiler success success

@yyx990803 yyx990803 merged commit 0b23fd2 into main May 1, 2025
16 checks passed
@yyx990803 yyx990803 deleted the edison/fix/12337 branch May 1, 2025 14:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. ready to merge The PR is ready to be merged. scope: reactivity
Projects
None yet
5 participants