Reactions Running code automatically when Signals change refresh-cw Guide
Categories

Reactions

A Reaction is a function that automatically re-runs whenever any Signal it depends on changes.

Reactions

A dependency is created when a Signal’s value is accessed (using .get() or .value) inside the function passed to reaction().

Creating a Reaction

To create a new reaction pass a function to reaction().

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 = signal(0);
// Create a reaction that logs the counter's value
const watcher = reaction(() => {
// Accessing counter.get() creates a dependency
console.log('counter:', counter.get());
});
// Update the signal, triggering the reaction
counter.set(1);
// alternatively
// counter.value = 1

Stopping a Reaction

You can use the .stop() method of a reaction to stop it from running.

// Stop the reaction created above
watcher.stop();
counter.set(2); // No output, reaction was stopped

Advanced Controls - For more ways to control reactivity and stop reactions see Reactive Controls.

Component Reactions

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.

Reactivity Example

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.
Previous
Derived Signals
Next
Mutations