State and derived values
Keep the data you actively change in state, and derive the values you can calculate. That gives every value a clear source.
Update state
Use MutableState.of() to set the initial value, next() to write a new value, and value to read the current one:
By default, state uses Object.is to compare values. When updating an object or array, create a new value and pass it to next(). Mutating the original object does not publish an update.
Derive a result from several inputs
A computation can depend on several states. Its result follows changes in any of them:
Keep these functions pure: calculate a result from the inputs and return it. Manage timers, event listeners, and other resources through the closure's lifecycle.
Publish several updates together
When several changes belong to one operation, group them with batch:
Subscribers do not receive a partially updated name. batch covers synchronous updates only. After an asynchronous operation finishes, use another batch to publish its results together.
Skip repeated work
Wrap a computation in memo when it is expensive or receives equivalent inputs repeatedly:
memo shallowly compares inputs by default and skips the computation when they are equivalent. It also compares results with Object.is to avoid publishing an unchanged result. Each rendered closure has its own cache.
If the computation returns an object, use the third argument to compare results:
A comparison function returns true for equivalent values. Add custom comparisons when they serve a need; most simple computations work well as plain functions.