On This Page
Reactive Variables
Setting Values
To create a reactive variable, you can use the ReactiveVar
class from the @semantic-ui/reactivity
package.
Accessing Values
To access the current value of a reactive variable, you can use get()
or value
To access a value without triggering reactivity you can use
peek
. See controlling reactivity.
Updating Values
To update the value of a reactive variable, you can use the set()
method, or any reactive helper function like now
, increment
Alternatively, you can directly assign a new value to the value
property:
Reactions
Reactive variables are typically used within a reactive context, this is a function that reruns when a reactive variable changes.
When a reactive variable is accessed within a reactive context, it establishes a dependency between the variable and the context. Whenever the value of the reactive variable changes, the reactive context is automatically re-run.
Creating a Reaction
In this example we set up a reaction by calling counter.get()
inside a reaction
.
Creating a Subscription
You can also use a subscription
to call a specific callback everytime a value changes without creating a reactive context.
Unlike a reaction
which tracks any reactive variable that is referenced and reruns when any value is updated a subscription will only rerun when a specified value is updated.
Subscriptions are an alternative approach to reactivity which prevent values in the callback from triggering reactivity.
Subscriptions return a reference to the current subscription. You can call subscription.stop()
to stop the callback from occurring.
Reactive Conditions
Equality Comparison
By default, reactive variables use a deep equality comparison to determine if the value has changed. This means that if you assign an object or array to a reactive variable, it will only trigger a reactive update if the contents of the object or array have changed.
You can customize the equality comparison function by passing a custom function as the second argument to the ReactiveVar
constructor:
Reactivity Example
ReactiveVar
are the only values that cause reactivity to occur in a reaction. When you create a Reaction
it will run immediately then re-run whenever a reactive value is updated.