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

Reactivity with Signals

Understanding Signals Based Reactivity

Reactivity put simply is values changing causes stuff to happen.

Signals are a mechanism for implementing reactivity that works by tracking the dependencies of a reactive value.

This is typically implemented using a value accessor or a get() function that tracks a reference to each time it is called, then re-runs each dependency when a value changes.

The value that changes is typically called a signal.

The function that re-runs when the value changes can be called many different things, for instance a watcher in the signals proposal, a computation like in Preact or simply watch like in Lit.

Naming Conventions - Semantic UI chooses to call a Signal a ReactiveVar which separates the implementation from the name. The function that changes is simply called a Reaction, making it easy to remember that a ReactiveVar causes a Reaction.

Usage

Semantic UI includes a package @semantic-ui/reactivity which exports ReactiveVar, Reaction, and Dependency and can be used as a standalone package without using Semantic UI components.

import { ReactiveVar, Reaction } from '@semantic-ui/reactivity';
const counter = new ReactiveVar(1);
Reaction.create(() => {
console.log(counter.value);
// outputs 1 2
});
counter.increment();

Usage in Components

If you are using @semantic-ui/component, reactivity is built into templating and available directly from lifecycle callbacks.

Learn more about reactivity in components in the dedicated component reactivity section.

Birthday Example

Imagine keeping a birthday calendar for your friends birthdays. Your friends birthdays on the calendar can be thought of as dependencies, they rely on knowing the current date to know if your friend’s birthday is today. In a signal based reactivity system you can view the current day as the signal.

When you wake up each day, you may look at the calendar and then compare the birthday to the circled birthdays on the calendar. This is like rerunning a calculation in your head.

This calculations is a reaction which depends on a source of truth, a signal or ReactiveVar.

const today = new ReactiveVar( new Date() );
// each day when you wake up
const setToday() => {
today.set(new Date());
}
const checkBirthdays = Reaction(() => {
const today = today.get();
if(today == friendsBirthday) {
// wish them happy birthday
}
else {
// no birthdays today
}
}