Skip to content

Commit d089f23

Browse files
feat: untrack
1 parent cc326a7 commit d089f23

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

packages/reactivity/__tests__/effect.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
pauseTracking,
2828
resetTracking,
2929
startBatch,
30+
untrack,
3031
} from '../src/effect'
3132

3233
describe('reactivity/effect', () => {
@@ -1182,6 +1183,17 @@ describe('reactivity/effect', () => {
11821183
expect(spy2).toHaveBeenCalledTimes(2)
11831184
})
11841185

1186+
it('should not track dependencies when using untrack', () => {
1187+
const value = ref(1)
1188+
let dummy
1189+
effect(() => {
1190+
dummy = untrack(() => value.value)
1191+
})
1192+
expect(dummy).toBe(1)
1193+
value.value = 2
1194+
expect(dummy).toBe(1)
1195+
})
1196+
11851197
describe('dep unsubscribe', () => {
11861198
function getSubCount(dep: Dep | undefined) {
11871199
let count = 0

packages/reactivity/src/effect.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,15 @@ export function resetTracking(): void {
537537
shouldTrack = last === undefined ? true : last
538538
}
539539

540+
export function untrack<T>(fn: () => T): T {
541+
try {
542+
pauseTracking()
543+
return fn()
544+
} finally {
545+
resetTracking()
546+
}
547+
}
548+
540549
/**
541550
* Registers a cleanup function for the current active effect.
542551
* The cleanup function is called right before the next effect run, or when the

0 commit comments

Comments
 (0)