UseCompute
UseCompute
is a hook that allows you to define a computation method ( computeValue
) to derive a value based on the current state of one or more dependencies. When any of these dependencies change, the hook recalculates the value
and provides the updated result.
Syntax
UseCompute
accepts these arguments:
-
computeValue
: A function that returns a value based on the current state of the dependencies. dependencies
: A list of state(RtState
, learn about it here) that the computation depends on. When any of these dependencies change, thevalue
is recalculated.
Properties & Methods
UseCompute
provides the following properties and methods:
value
: A getter that allows you to read the computed value.
-
Methods inherited from
RtState
(Learn more here):-
update
: A method to notify changes after run a set of instructions. -
refresh
: A method to force to notify changes. - *
bind
: A method to bind an instance to it. - *
unbind
: A method to unbind an instance to it. - *
dispose
: A method to remove all listeners and free resources.
-
Usage
Declaration
UseCompute
can be initialized using the constructor class:
Reading the computed value
UseCompute
has a value
property that allows you to read the computed value:
Computing the value
When any of the dependencies
change, the value
property recalculates the result based on the computeValue
function, e.g.:
In above example, the value
of uResult
will be recalculated when the value
of uStateA
or uStateB
changes.
But when the calculated value
is same as the previous value
, it will not notify the change.
Using with Memo
UseCompute
does not cache the computed value
, meaning that it will computing the value
every time the dependencies
is changed, potentially impacting performance, especially if the computeValue
is expensive. In this case, you should consider using Memo
to cache the computed value
, e.g.:
Updating the value
Use update
method to notify changes after run a set of instructions:
Use refresh
method to force to notify changes.
Listening to changes
When value
has changed, the UseCompute
will emit the following events(learn about it here):
Lifecycle.willUpdate
event is triggered before thevalue
change orupdate
,refresh
methods have been invoked.Lifecycle.didUpdate
event is triggered after thevalue
change orupdate
,refresh
methods have been invoked.
Example of listening to changes: