Nested object references are shared when using createStore #3007
Replies: 1 comment 2 replies
-
I think that's by design that Jotai doesn't clone the initial value. It's not trivial (e.g. If Jotai would clone the initial value, your code would still not work in some cases. For example, if you have a derived atom that returns the nested object, the components reading this atom would not re-render because you mutated the object so it's still the same reference. You can use export const basicAtom = atomWithDefault<BasicObject>(() => ({ /* ... */ })); And when updating atom values, I recommend to create new objects instead of mutating them. You can use Immer and Jotai also has an integration for Immer |
Beta Was this translation helpful? Give feedback.
-
Bug Description
When an atom with nested objects is created and reused in different stores the nested objects are not cloned. Resulting in each atom keeping the reference to the original object. This result in problems when updating the data in one store and getting the same changes in another store. This second store is not immediately updated because
Object.is
will not detect this until the atom in the second store is also updated.Reproduction Link
https://stackblitz.com/edit/vitejs-vite-31argexu?file=src%2FApp.tsx
Beta Was this translation helpful? Give feedback.
All reactions