Exploring Valtio, another module state library
Valtio is a library primarily used for module state, which is the same as Zustand.
As we learned in Chapter 7, Use Case Scenario 1 – Zustand, we create a store in Zustand as follows:
const store = create(() => ({ count: 0, text: "hello", }));
The store
variable has some properties, one of which is setState
. With setState
, we can update the state. For example, the following is incrementing the count
value:
store.setState((prev) => ({ count: prev.count + 1, }))
Why do we need to use setState
to update a state value? Because we want to update the state immutably. Internally, the previous setState
works like the following:
moduleState = Object.assign({}, moduleState, { count: moduleState.count + 1 });
This is the way to update an object immutably.
Let's imagine a case where we don't need to follow the immutable update rule. In this case...