
Enter a search term above to see results...
Enter a search term above to see results...
A Reaction
is a function that automatically re-runs whenever any Signal it depends on changes.
A dependency is created when a Signal’s value is accessed (using .get()
or .value
) inside the function passed to Reaction.create()
.
To create a new reaction pass a function to Reaction.create()
.
The reaction will immediately run to determine its dependencies, and then rerun in the next flush cycle when its dependencies change .
import { Signal, Reaction } from '@semantic-ui/reactivity';
const counter = new Signal(0);
// Create a reaction that logs the counter's valueconst reaction = Reaction.create(() => { // Accessing counter.get() creates a dependency console.log('counter:', counter.get());});
// Update the signal, triggering the reactioncounter.set(1);
// alternatively// counter.value = 1
You can use the .stop()
method of a reaction to stop it from running.
// Stop the subscription created abovereaction.stop();
counter.set(2); // No output, reaction was stopped
Advanced Controls - For more ways to control reactivity and stop reactions see Reactive Controls.
Reactions are the foundation for reactivity within component templates and can be created directly from component lifecycle events.
Components For more information on reactions inside components see Component Reactivity.
The following example shows the difference between a reactive variable (Signal) and a regular variable in a Reaction.
person1
is a Signal and when its value is updated the function reruns.person2
is a regular javascript variable and does not cause the reaction to rerun when changed.As an alternative to Reactions, you can use a Signal’s .subscribe()
method to execute a specific callback only when that particular Signal changes.
Unlike a Reaction, a subscription callback does not automatically track dependencies on other signals accessed within it. It simply runs in response to changes in the subscribed Signal.
import { Signal } from '@semantic-ui/reactivity';
const name = new Signal('Alice');
const subscription = name.subscribe((newValue, oldValue) => { console.log(`Name changed from ${oldValue} to ${newValue}`);});
name.set('Bob'); // Output: Name changed from Alice to Bobname.set('Charlie'); // Output: Name changed from Bob to Charlie
The .subscribe()
method returns a subscription object with a .stop()
method, allowing you to manually unsubscribe and prevent the callback from running on future changes.
// Stop the subscription created abovesubscription.stop();
// No output, subscription was stoppedname.set('David');
Subscriptions are useful for triggering side effects directly in response to a specific state change without the overhead or complexity of a full reactive context.