Why doesn't Zustand incorporate Immer for a cleaner API? #738
-
In simple applications, it's fine to update the state by destructuring. But in more complex applications, with nested objects, Immer is absolutely necessary in order to keep our sanity. However, there is a continuous boilerplate with import produce from 'immer'
const useStore = create(set => ({
lush: { forest: { contains: { a: "bear" } } },
clearForest: () => set(produce(state => {
state.lush.forest.contains = null
}))
})) If Immer was incorporated, it could be hypothetically written as: import produce from 'immer'
const useStore = create(set => ({
lush: { forest: { contains: { a: "bear" } } },
clearForest: () => set(state => {
state.lush.forest.contains = null
})
})) So the state would be mutable by default. The difference may not look that much here, but in a store with lots of methods, IMHO it would make a difference. Is this a feasible idea? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
While I personally prefer And, my general recommendation for mutable state is valtio instead of zustand+immer combo. With zustand, I started promoting some other solutions with more functional and immutable approaches: https://github.com/pmndrs/zustand/wiki/Updating-nested-state-object-values That said, people like using zustand with immer, and it's totally a valid solution. |
Beta Was this translation helpful? Give feedback.
While I personally prefer
produce
(to me, it's more explicit withproduce
anddraft
, not boilerplatey at all), zustand can be used withimmer
middleware described in https://github.com/pmndrs/zustand#middleware. I think many people are using zustand with immer.And, my general recommendation for mutable state is valtio instead of zustand+immer combo. With zustand, I started promoting some other solutions with more functional and immutable approaches: https://github.com/pmndrs/zustand/wiki/Updating-nested-state-object-values
That said, people like using zustand with immer, and it's totally a valid solution.
So, we will probably consider adding the official
immer
middleware in zustand v4.T…