# Thinking in signals
A RemedyUI component is a function that runs once. It builds elements and connects them to
state. When the state changes, only the properties that read it update. Nothing re-runs the
component, nothing diffs a tree, and nothing runs while nothing changes.
The state lives in [`Signal`](crate::reactive::Signal)s. Values computed from it are
[`Memo`](crate::reactive::Memo)s. Work that follows it is an
[`Effect`](crate::reactive::Effect), or more often a binding on an element
([`El::bind`](crate::El::bind), and properties given a closure or a signal). This page shows each of them, then
batching, untracked reads and who owns what.
## Signals
A signal holds one value. Reading it inside a memo, effect or binding subscribes that reader;
writing it updates exactly the readers that read it.
```
use remedy_ui::reactive::Signal;
let count = Signal::new(0u32);
count.set(2);
let names = Signal::new(vec!["Ada".to_string(), "Grace".to_string()]);
assert_eq!(names.with(|n| n.len()), 2);
```
A `Signal` is a `Copy` handle, so closures capture it by value with no `Rc` or `clone`. Its
value lives in the UI thread's reactive runtime, and only that thread can reach it.
- [`set`](crate::reactive::Signal::set) and [`update`](crate::reactive::Signal::update)
always notify readers.
- [`set_if_changed`](crate::reactive::Signal::set_if_changed) notifies only when the new
value differs, for values that are often written with what they already hold.
- [`take`](crate::reactive::Signal::take) moves the value out and leaves the default.
## Memos
A memo is a value derived from signals. It runs again only when something it read changed,
and when its new value equals the old one it stops there: nothing downstream runs.
```
use remedy_ui::reactive::{Effect, Memo, Signal};
use std::cell::Cell;
use std::rc::Rc;
let text = Signal::new("hello".to_string());
let runs = Rc::new(Cell::new(0));
let r = runs.clone();
Effect::new(move || {
let _ = words.get();
r.set(r.get() + 1);
});
assert_eq!(runs.get(), 1);
text.set("hello world".into()); // two words: the effect runs
assert_eq!(runs.get(), 2);
text.set("hello there".into()); // still two words: the memo stops the change
assert_eq!(runs.get(), 2);
```
Memos need `PartialEq`, which is how they know a value did not change. They are lazy: a
memo nobody reads does not run.
## Effects
An effect runs once when created and again whenever a signal it read changes. Effects are
for work outside the UI: saving a draft, logging, telling another part of the app. Effects
never see half-updated state: when two signals change together, the effect runs once, after
both.
```
use remedy_ui::reactive::{Effect, Signal};
use std::cell::RefCell;
use std::rc::Rc;
let draft = Signal::new(String::new());
let saved = Rc::new(RefCell::new(Vec::new()));
let s = saved.clone();
draft.set("Hi".into());
draft.set("Hi there".into());
assert_eq!(*saved.borrow(), ["", "Hi", "Hi there"]);
```
An effect tracks what it read on its latest run, not what it might read. A branch that was
not taken subscribes nothing, so there are no dependency lists to keep right.
## Binds: signals on elements
On elements, use a binding instead of a free-standing effect. A binding is an effect that
belongs to its element: it runs while the element lives and is disposed with it.
- [`El::text`](crate::El::text): the element's text.
- [`El::style`](crate::El::style): its local style.
- [`El::disabled`](crate::El::disabled): whether it can be used.
- [`El::variant`](crate::El::variant): which variant of its widget it shows.
- [`El::semantics`](crate::El::semantics): what it tells screen readers.
- The widgets' labels: [`widgets::text`](crate::widgets::text),
[`widgets::button`](crate::widgets::button) and the rest.
- [`El::bind`](crate::El::bind): anything else.
Each of these takes an [`IntoProp`](crate::view::IntoProp): a plain value sets it once and
creates no binding, while a [`Signal`](crate::reactive::Signal), a
[`Memo`](crate::reactive::Memo) or a closure binds it. Making a property follow state never
changes the call's shape.
Each one marks only the work its change needs. A new text relays out that text and repaints
it; a new color only repaints.
```
# use remedy_ui::AppConfig;
# use remedy_ui::testing::TestApp;
use remedy_ui::reactive::Signal;
use remedy_ui::widgets as w;
use remedy_ui::{App, WindowSpec};
let count = Signal::new(0u32);
let add = w::button(ui, "Add one", move || count.update(|c| *c += 1));
let shown = w::text(ui, move || format!("Count: {}", count.get()));
let reset = w::button(ui, "Reset", move || count.set(0)).disabled(move || count.get() == 0);
ui.root().child(add).child(shown).child(reset);
});
};
# let mut test = TestApp::new(AppConfig::new("Counter"), app);
# let Some(ui) = test.ui() else { unreachable!("the window is open") };
# let shows = |ui: &remedy_ui::Ui, name: &str| ui.reader_view().iter().any(|n| n.name.as_deref() == Some(name));
assert!(shows(&ui, "Count: 0"));
count.set(2); // from a handler, a timer, a background result...
test.frames(1);
assert!(shows(&ui, "Count: 2"));
```
The component ran once. Setting `count` re-ran two small closures: the text and the
disabled state.
When a value is the same for the element's whole life, pass the value, not a closure. A
constant creates no binding at all. When it is exactly a signal's value, pass the signal
itself: `w::text(ui, status)` follows `status`.
## Batching
Writes inside [`batch`](crate::reactive::batch) notify once, when the batch ends. Each event
handler, timer and posted closure already runs in a batch, so most code never calls it.
Call it yourself when you change several signals from somewhere else, such as a test or a
setup function.
```
use remedy_ui::reactive::{Effect, Signal, batch};
use std::cell::RefCell;
use std::rc::Rc;
let first = Signal::new("Ada".to_string());
let last = Signal::new("Lovelace".to_string());
let seen = Rc::new(RefCell::new(Vec::new()));
let s = seen.clone();
batch(|| {
first.set("Grace".into());
last.set("Hopper".into());
});
// One run for the batch: no effect ever saw "Grace Lovelace".
assert_eq!(*seen.borrow(), ["Ada Lovelace", "Grace Hopper"]);
```
## Reading without subscribing
Sometimes a binding needs a value without following it: the current theme for a one-off
calculation, or a signal it writes to. Wrap the read in
[`untrack`](crate::reactive::untrack), or use
[`get_untracked`](crate::reactive::Signal::get_untracked).
```
use remedy_ui::reactive::{Effect, Signal, untrack};
use std::cell::Cell;
use std::rc::Rc;
let query = Signal::new(String::from("rust"));
let page_size = Signal::new(20usize);
let runs = Rc::new(Cell::new(0));
let r = runs.clone();
let size = untrack(|| page_size.get());
let _ = (q, size);
r.set(r.get() + 1);
});
page_size.set(50); // read untracked: the search does not run again
assert_eq!(runs.get(), 1);
query.set("signals".into());
assert_eq!(runs.get(), 2);
```
`get_untracked` returns a `Result`, because outside a binding there is no nearby owner to
report a disposed signal to.
## Lifetimes
Every signal, memo and effect has an owner: the [`Scope`](crate::reactive::Scope), memo or
effect that was running when it was made. Disposing an owner disposes everything it owns and
runs its clean-ups ([`on_cleanup`](crate::reactive::on_cleanup)).
- An element's bindings are owned by the element. Removing the element
([`El::remove`](crate::El::remove)) disposes them, and runs its
[`El::on_removed`](crate::El::on_removed) callbacks.
- A list row built by [`widgets::for_each`](crate::widgets::for_each) lives as long as its
key stays in the list.
- Signals made at the top of a component, outside any scope, live until you dispose them.
Give long-lived state one home (the app's state struct) instead of making new signals in
code that runs often.
```
use remedy_ui::reactive::{Effect, Scope, Signal, on_cleanup};
use std::cell::Cell;
use std::rc::Rc;
let online = Signal::new(true);
let cleaned = Rc::new(Cell::new(false));
let c = cleaned.clone();
Effect::new(move || status.set(if online.get() { "Online" } else { "Offline" }));
on_cleanup(move || c.set(true));
status
});
online.set(false);
assert_eq!(status.get(), "Offline");
scope.dispose();
assert!(cleaned.get(), "clean-ups run on dispose");
assert!(!status.is_alive(), "what the scope owned is gone");
assert!(status.try_get().is_err(), "reading it says so instead of inventing a value");
```
A clean-up registered inside an effect runs before the effect's next run as well, so an
effect that starts something (a timer, a subscription) can stop it each time.
## Context
Some values belong to a whole subtree rather than to one component: the document a screen
edits, the account that is signed in, a service. Instead of passing them through every
function, provide them on an element with [`El::provide`](crate::El::provide), and read the
nearest one below it with [`El::use_context`](crate::El::use_context), or with
[`reactive::use_context`](crate::reactive::use_context) in code built inside it
([`El::child_with`](crate::El::child_with), its bindings). A value that changes is provided
as a signal.
```
use remedy_ui::reactive::Signal;
use remedy_ui::testing::TestApp;
use remedy_ui::widgets as w;
use remedy_ui::{El, Ui};
/// Who is signed in, for everything under the account screen.
#[derive(Clone, Copy)]
struct Account {
name: Signal<String>,
}
/// A greeting that finds the account itself, wherever it is placed below.
fn greeting(ui: &Ui) -> El {
let account = remedy_ui::reactive::use_context::<Account>();
w::text(ui, move || match account {
Some(a) => format!("Signed in as {}", a.name.get()),
None => "Not signed in".into(),
})
}
let name = Signal::new("Ada".to_string());
provided as context ([`App::persist_store`](crate::App::persist_store)), which is where
`persist` saves. It is flushed when the app quits, is suspended, or goes out of sight (every
window hidden or covered, a page's tab hidden), since a phone or a browser may end an app
from there without another word. Where it keeps things, by platform:
| Windows | `%APPDATA%\<app name>\state\<key>.json` |
| macOS | `~/Library/Application Support/<app name>/state/<key>.json` |
| Linux | `$XDG_CONFIG_HOME/<app name>/state/<key>.json` (or `~/.config/…`) |
| Android | the app's private internal storage: `/data/user/<user>/<package>/files/state/<key>.json` |
| Browser page | the origin's `localStorage`, key `remedy:<app name>:<key>` |
The folder is the app's data folder ([`App::data_dir`](crate::App::data_dir), or the one
[`AppConfig::data_dir`](crate::AppConfig::data_dir) names); keys with characters other than
letters, digits, `.`, `-` and `_` are escaped in file names. A page has no folder (`data_dir`
is `None` there), so its store keeps the same versioned JSON in `localStorage`, under a prefix
per app (`~` and `:` in the app's name are written `~7e` and `~3a`) so apps sharing an origin
keep apart. A browser keeps an origin's `localStorage` across reloads and restarts, and
installed web apps keep theirs until the person clears the site's data; it holds a few
megabytes per origin, and a write the browser refuses is reported by
[`PersistStore::take_errors`](crate::reactive::PersistStore::take_errors) and
[`flush`](crate::reactive::PersistStore::flush), with the value still seen by loads until a
later write lands it.
A value other code shares is kept plain instead: [`Persist::plain`](crate::reactive::Persist::plain)
keeps it alone, with no version around it, under exactly its key. In a page that is the
origin's own `localStorage` item of that name, outside the app's prefix, so an older web
version of the app on the same origin reads and writes the same item, and a choice made in
either survives a reload of both; on the desktop it is the key's file in the same folder,
holding just the value. [`Plain::Json`](crate::reactive::Plain::Json) writes the value as
`JSON.stringify` does, [`Plain::Text`](crate::reactive::Plain::Text) a string as the string
itself (`localStorage.setItem("theme", "dark")`). Plain values have no version or migration,
so read what another program writes leniently (serde defaults for fields it may leave out).
[`Persist::session`](crate::reactive::Persist::session) keeps a plain value for the session
only: in a page, the tab's own `sessionStorage` item (shared with the origin's other pages in
that tab, gone with the tab); elsewhere, memory for the app's run. It is written at once,
with no debounce. [`PersistStore::forget`](crate::reactive::PersistStore::forget) removes a
value of any kind.
```
use remedy_ui::reactive::{Persist, Plain, Signal};
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
struct Fonts {
#[serde(default)]
text: String,
#[serde(default)]
headings: String,
}
# fn setup() {
// The items the old page keeps: `portal-theme` is "midnight", `portal-fonts` is
// {"text":"remedy-sans","headings":"ahmi-pixel"}.
let theme = Signal::new("portal".to_owned()).persist(Persist::new("portal-theme").plain(Plain::Text));
let fonts = Signal::new(Fonts { text: "remedy-sans".into(), headings: "ahmi-pixel".into() })
.persist(Persist::new("portal-fonts").plain(Plain::Json));
// `portal-seasons` is in the tab's sessionStorage.
let seasons = Signal::new(serde_json::Value::Null).persist(Persist::new("portal-seasons").session());
# let _ = (theme, fonts, seasons);
# }
```
Window geometry ([`WindowSpec::persist_geometry`](crate::WindowSpec::persist_geometry)) is kept
beside it, in `windows.txt` in the data folder, and in a page in the same store
(`remedy:<app name>:remedy-ui.windows`), so floating windows come back where they were.
### The app's own documents
The store is also the one way to keep an app's own data that works on every platform,
browser pages included: [`save`](crate::reactive::PersistStore::save) and
[`load`](crate::reactive::PersistStore::load) take any serializable value under a key, with
the same versions and migrations as persisted signals, and
[`remove`](crate::reactive::PersistStore::remove) forgets one. A load sees a save at once,
before the debounced write lands. A recipe calculator keeping its library:
```no_run
use remedy_ui::reactive::Persist;
use remedy_ui::{App, AppConfig};
// A recipe: its name and its oils in grams (an app's own types derive `serde`'s traits).
type Recipe = (String, Vec<(String, f64)>);
remedy_ui::run(AppConfig::new("Craft Calc"), |app: &App| {
let Some(store) = app.persist_store() else { return };
let library = Persist::new("recipes");
let mut recipes: Vec<Recipe> = store.load(&library).ok().flatten().unwrap_or_default();
recipes.push(("Castile".into(), vec![("Olive".into(), 1000.0)]));
// Written after the debounce, and before the app quits or goes to the background.
if let Err(e) = store.save(&library, &recipes) {
eprintln!("the library was not saved: {e}");
}
})
.ok();
```
A value
whose shape changes over releases takes a [`Persist`](crate::reactive::Persist) with a
version and a migration from older versions; a file from a newer version of the app is left
alone. [`Signal::persist_in`](crate::reactive::Signal::persist_in) saves in a store the app
opens itself:
```
use remedy_ui::reactive::{Persist, PersistStore, Scope, Signal, batch};
let dir = std::env::temp_dir().join(format!("remedy-guide-persist-{}", std::process::id()));
let store = PersistStore::open(&dir)?;
let ((), first_run) = Scope::new(|| {
let split = Signal::new(0.3f32).persist_in(&store, Persist::new("split")).unwrap_or_else(|(s, _)| s);
split.set(0.6);
});
first_run.dispose();
// The next start: the value comes back.
let app = move |app: &App| {
// A slow computation off the UI thread; the window stays responsive meanwhile.
// Keep the job to cancel it; once cancelled, `done` never runs.
let _job = app.background_cancellable(
|cancelled| {
let mut h = 0u64;
for i in 0..5_000_000u64 {
if i % 100_000 == 0 && cancelled.is_cancelled() {
break;
}
h = h.rotate_left(5) ^ i;
}
h.to_string()
},
move |result| digest.set(result),
);
app.open(WindowSpec::new("Hasher"), move |ui, _| {
ui.root().child(w::text(ui, digest));
});
};
let mut test = TestApp::new(AppConfig::new("Hasher"), app);
for _ in 0..10_000 {
if digest.get() != "Working…" {
break;
}
std::thread::yield_now();
test.frames(1);
}
assert_ne!(digest.get(), "Working…", "the result came back to the UI thread");
```
## Collections and nested state
- [`SignalVec`](crate::reactive::SignalVec) is a list that records what changed (push,
insert, remove, move, set) instead of handing out new copies. Readers take the changes
with a [`VecReader`](crate::reactive::VecReader).
- [`Store`](crate::reactive::Store) tracks a nested structure field by field, so a write to
one message's `edited` flag wakes readers of that field and not its siblings.
The list widgets take either a `Signal<Vec<T>>` or a `SignalVec`, whose operations they apply
row by row; see [`crate::guide::lists`].
## Finding out why something updated
Give important signals a name with
[`Signal::named`](crate::reactive::Signal::named). The inspector's Signals page (feature
`devtools`, F12 in a debug build) shows each element's bindings, what they read, and a log
such as "row “42” relaid out because its text binding re-ran: `message.text` changed".