Reactivity with Signals Learn how Semantic UI uses signals to produce reactivity cpu Guide

Reactivity with Signals

Understanding Reactivity

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

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.

Reactions

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 a watcher, in Preact a computation and in Lit simply watch.

Usage

Standalone Usage

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();

Component Integration

When building Semantic UI components, the reactivity system is seamlessly integrated:

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);
});
}
});

Example

Birthday Calendar

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:

  1. Signal - Depending on today
  2. Reaction - If any of my friends’ birthdays are today wish them a happy birthday

This could be represented in code like this:

const today = new Signal( new Date() );
// change signal
const newDay() => {
today.set(new Date());
}
// rerun reaction
const checkBirthdays = Reaction.create(() => {
const currentDay = today.get(); // depend on day of year
// check birthdays
each(friendsBirthdays, (person) => {
if(currentDay == person.birthday) {
happyBirthday(person.name);
}
});
}
Previous
Helpers
Next
Signals