Reactive Controls Controlling the behavior of Reactions using the instance passed to the callback. sliders Guide

Reactive Controls

Creating a Reaction using Reaction.create() will provide the Reaction instance itself as the first argument.

const mySignal = new Signal(0);
Reaction.create((reaction) => { // reaction is the Reaction instance
console.log('Current value:', mySignal.get());
// do something with reaction
});

The reaction instance can be used to control the execution of your reaction after it runs under certain conditions.

Controlling Reactions

Stopping a Reaction

You can permanently stop a reaction from running again, even if its Signal dependencies change, by calling the reaction.stop() method.

Once stopped, the reaction will no longer track dependencies or execute its callback.

import { Signal, Reaction } from '@semantic-ui/reactivity';
const percentComplete = new Signal(0);
Reaction.create((reaction) => {
const currentPercent = percentComplete.get();
if(currentPercent < 100) {
// updateProgress(currentPercent);
console.log('Progress:', currentPercent);
}
else {
console.log('Progress complete, stopping reaction.');
reaction.stop();
}
});
progress.increment(80);
progress.increment(20); // at 100 stopping
progress.increment(50); // over 100 no longer updating

Adjusting First Execution

The reaction.firstRun property (boolean) can be used to determine if the reaction is on its first execution.

This can be useful if you have special conditions for the initial run, or would like to prevent some side effects from running the first time code runs.

Special Conditions
import { Signal, Reaction } from '@semantic-ui/reactivity';
const score = new Signal(0);
// Don't show the score unless the user has scored points
Reaction.create((reaction) => {
const currentScore = score.get();
if (!reaction.firstRun) {
console.log(`Score: ${currentScore}`);
}
});

Common Pitfalls

Be sure that any Signal accesses (.get() or .value) necessary for your function are reachable during the first run, otherwise they will not be tracked as dependencies.

Special Conditions
import { Signal, Reaction } from '@semantic-ui/reactivity';
const score = new Signal(0);
// This will never rerun because score.get() is never reached on first run
Reaction.create((reaction) => {
if (!reaction.firstRun) {
console.log(`Score: ${score.get()}`);
}
});
Previous
Flushing
Next
Performance