Skip to content

Commit

Permalink
fix(vanilla): avoid re-computing unmounted derived atoms in an edge c…
Browse files Browse the repository at this point in the history
…ase (#2197)

* fix: store bug

* fix to pass the test

---------

Co-authored-by: daishi <[email protected]>
Co-authored-by: Daishi Kato <[email protected]>
  • Loading branch information
3 people authored Oct 23, 2023
1 parent 6c9e030 commit 4cd3564
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,9 +368,17 @@ export const createStore = () => {
// Otherwise, check if the dependencies have changed.
// If all dependencies haven't changed, we can use the cache.
if (
Array.from(atomState.d).every(
([a, s]) => a === atom || readAtomState(a) === s
)
Array.from(atomState.d).every(([a, s]) => {
if (a === atom) {
return true
}
const aState = readAtomState(a)
return (
aState === s ||
// We need to check values in case only dependencies are changed
(aState && isEqualAtomValue(aState, s))
)
})
) {
return atomState
}
Expand Down
12 changes: 12 additions & 0 deletions tests/vanilla/store.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,15 @@ it('should update derived atoms during write (#2107)', async () => {
store.set(countAtom, 2)
expect(store.get(countAtom)).toBe(2)
})

it('should not recompute a derived atom value if unchanged (#2168)', async () => {
const store = createStore()
const countAtom = atom(1)
const derived1Atom = atom((get) => get(countAtom) * 0)
const derive2Fn = vi.fn((get: Getter) => get(derived1Atom))
const derived2Atom = atom(derive2Fn)
expect(store.get(derived2Atom)).toBe(0)
store.set(countAtom, (c) => c + 1)
expect(store.get(derived2Atom)).toBe(0)
expect(derive2Fn).toHaveBeenCalledTimes(1)
})

1 comment on commit 4cd3564

@vercel
Copy link

@vercel vercel bot commented on 4cd3564 Oct 23, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.