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(vanilla): avoid re-computing unmounted derived atoms in an edge case #2197

Merged
merged 3 commits into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
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)
})
Loading