
Enter a search term above to see results...
Enter a search term above to see results...
Reactivity is the mechanism by which changes in data automatically propagate to update dependent code or UI elements. Semantic UI implements reactivity using Signals.
See the Reactivity API Reference for a full reference guide to the classes and methods of the reactivity library.
Signals are reactive primitives that hold a value and track dependencies. When a signal’s value changes, it notifies any reactive contexts, (reactions) that they need to re-run.
Signals track dependencies automatically when their value is accessed (e.g., via .value
or .get()
) within a reactive context.
A Reaction is a function designed to re-run automatically whenever any signal it depends on changes. Accessing a signal’s value inside a reaction creates this dependency.
Naming Reactivity Signals implementations vary in their naming conventions for a reactive context. In Semantic UI it is called a
reaction
, in the signals proposal awatcher
, in Preact acomputation
and in Lit simplywatch
.
The @semantic-ui/reactivity
package can be used independently from the component framework. It exports core classes Signal
, Reaction
, and Dependency
.
import { Signal, Reaction } from '@semantic-ui/reactivity';
const counter = new Signal(1);
Reaction.create(() => { console.log(counter.value); // outputs 1 2});counter.increment();
When building Semantic UI components, the reactivity system is seamlessly integrated:
signal
(to create new signals) and reaction
(to create reactive computations scoped to the component’s lifecycle).Learn more about using reactivity within components in the dedicated Component Reactivity guide.
const createComponent = ({ self, reaction, signal }) => ({ value: signal(0), initialize() { // this will log whenever the value updates reaction(() => { console.log(self.value); }); }});
A simple way to think about reactivity is to imagine how a person might consider when their friend’s birthdays might occur. Each day you wake up you run a “reaction” to determine if today is your friends’ birthdays. This is because the “signal” the day of the year, has changed overnight meaning you will need to rerun the computation. “Is today any of my friends’ birthdays”.
You might use a simple system like:
This could be represented in code like this:
const today = new Signal( new Date() );
// change signalconst newDay() => { today.set(new Date());}
// rerun reactionconst checkBirthdays = Reaction.create(() => { const currentDay = today.get(); // depend on day of year
// check birthdays each(friendsBirthdays, (person) => { if(currentDay == person.birthday) { happyBirthday(person.name); } });}