Should initialState be immutable? #3035
Replies: 1 comment 3 replies
-
Yes, it should as well as non-initial state. Everything is built on the immutability contract.
I wasn't aware that many devs assume that. In such a case, one might consider deep freezing the state object during the development.
No it doesn't. If this is only about testing env, deep freezing might be a good option. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The
initialState
can be mutated after the store is created, sometimes in subtle ways. Consider the following example:To demonstrate the mutation we can use the following tests:
Note
I am using the instructions on setting up vitest found here to mock zustand so the store is reset
afterEach
test.The way the
zustand.ts
mock file handles resetting the store is using thegetInitialState
api method:I totally get it—I shouldn't mutate the object for a bear. However, many developers might assume that immutability only applies or is necessary at the top level (the array) rather than to the objects inside it. That said, if I call
getInitialState
, it seems reasonable to expect a deep copy of whatever was originally passed intocreate
, especially in a testing environment.Does it make sense for
getInitialState
to return a deep copy in this case, or is there a better way to handle this kind of issue?Beta Was this translation helpful? Give feedback.
All reactions