Skip to content
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

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/reactivity/__tests__/computed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,17 @@ describe('reactivity/computed', () => {
expect(cValue.value).toBe(1)
})

test('should not recompute if computed does not track reactive data', async () => {
const spy = vi.fn()
const c1 = computed(() => spy())

c1.value
ref(0).value++ // update globalVersion
c1.value

expect(spy).toBeCalledTimes(1)
})

test('computed should remain live after losing all subscribers', () => {
const state = reactive({ a: 1 })
const p = computed(() => state.a + 1)
Expand Down
11 changes: 6 additions & 5 deletions packages/reactivity/src/effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export enum EffectFlags {
DIRTY = 1 << 4,
ALLOW_RECURSE = 1 << 5,
PAUSED = 1 << 6,
EVALUATED = 1 << 7,
}

/**
Expand Down Expand Up @@ -377,22 +378,21 @@ export function refreshComputed(computed: ComputedRefImpl): undefined {
}
computed.globalVersion = globalVersion

const dep = computed.dep
computed.flags |= EffectFlags.RUNNING
// In SSR there will be no render effect, so the computed has no subscriber
// and therefore tracks no deps, thus we cannot rely on the dirty check.
// Instead, computed always re-evaluate and relies on the globalVersion
// fast path above for caching.
if (
dep.version > 0 &&
!computed.isSSR &&
computed.deps &&
!isDirty(computed)
computed.flags & EffectFlags.EVALUATED &&
(!computed.deps || (computed.deps && !isDirty(computed)))
) {
computed.flags &= ~EffectFlags.RUNNING
edison1105 marked this conversation as resolved.
Show resolved Hide resolved
return
}
computed.flags |= EffectFlags.RUNNING

const dep = computed.dep
const prevSub = activeSub
const prevShouldTrack = shouldTrack
activeSub = computed
Expand All @@ -402,6 +402,7 @@ export function refreshComputed(computed: ComputedRefImpl): undefined {
prepareDeps(computed)
const value = computed.fn(computed._value)
if (dep.version === 0 || hasChanged(value, computed._value)) {
computed.flags |= EffectFlags.EVALUATED
computed._value = value
dep.version++
}
Expand Down