Computed state and selectors
Every RjObject has its own selectors: a collection functions used to select a piece of internal state. In addition the RjObject olds a function to compute the state given to its consumers.
#
Default selectorsWhen you crafting a new RjObject default selectors are generated. Default selectors are designed to work with default state shape and are:
- getRoot: select the root state.
- isPending: select the pending state from root state.
- isLoading: alias for isPending
- getError: select the error state from root state.
- getData: select the data state from root state.
You can access selectors using the makeSelectors function on RjObject.
#
Extending selectorsYou can use selectors option on RocketJump constructor to add custom selectors and compose with defaults.
The final CoolState
RjObject has default selectors plus getCounter
and getName
.
#
Compute stateWhen a RjObject is consumed the state from reducer isn't used directly, but the consumer use a function called computeState on RjObject itself. The computeState function take the state from reducer and the RjObject selectors to provide you the computed state.
When you use consumers such useRj
this is done for you:
The default computeState implementation simply select the root state.
You can change the value returned from computeState using computed option, an object that map out property with internal RocketJump state. Computed values can be inline selectors or strings that refernces selectors names.
Using configuration from previous example.
The computedState
has this shape:
#
Memoizing selectorscaution
In most of apps you dont' need to memoize RocketJump selectors.
You can simply rely on React's useMemo
inside your components.
RocketJump selectors are created per instance when you consume your RjObject. So you can create per instance memoizing version of your selectors: