The pros and cons of this approach
We have seen how Valtio works and one question is when we should use it and when we should not.
One big aspect is the mental model. We have two state-updating models. One is for immutable updates and the other for mutable updates. While JavaScript itself allows mutable updates, React is built around immutable states. Hence, if we mix the two models, we should be careful not to confuse ourselves. One possible solution would be to clearly separate the Valtio state and React state so that the mental model switch is reasonable. If it works, Valtio can fit in. Otherwise, maybe stick with immutable updates.
The major benefit of mutable updates is we can use native JavaScript functions.
For example, removing an item from an array with an index
value can be written as follows:
array.splice(index, 1)
In immutable updates, this is not so easy. For example, it can be written with slice
, as follows:
[...array.slice(0, index), ...array.slice...