State and computed values
Update local fields, share reactive handles and derive cached values.
On this page
Start with ordinary local state
Declare retained state directly in <rust>, for example let count: u32 = 0;. The compiler generates the cloneable State and initializes it once per mount. Event handlers receive &mut State and a Context. Mutating a field during a handler causes Inrux to publish an updated description.
fn increment(state: &mut State, _: &Context<State>) {
state.count += 1;
}
You do not need an effect to copy state.count into a Text node. Bind the Text expression directly to count. Arbitrary Rust local variables do not become reactive on their own.
Use Signal for shared dependencies
use inrux::{Computed, Signal};
let count: Signal<u32> = Signal::new(2_u32);
let source = count.clone();
let doubled: Computed<u32> = Computed::new(move || source.get() * 2);
assert_eq!(doubled.get()?, 4);
count.update(|value| *value += 1);
assert_eq!(doubled.get()?, 6);
This fragment belongs in a function that returns a compatible Result. Computed::get can fail; handle the result instead of assuming it cannot.
A cloned Signal shares its value. A new Signal creates independent state. Computed tracks the sources its getter reads, caches the result, and reevaluates when those sources change. Keep getters pure: no I/O, mutations or background work. Put conditional labels, classes and derived layout values in the <rust> block as named computed values; the <view> binds to their results. Create the source Signals and Computed handles once at the top level of <rust>, and clone the Signals into each getter. See the AspectRatio example for a complete file. For values derived directly from incoming plain props, use a pure Rust getter that reads the latest props.
Write composables as Rust functions
Put reusable state construction in src/composables/. A use_counter function can return a struct containing a Signal and a Computed. Create those handles in the <rust> initialization block; rebuilding them while evaluating the view discards their history and dependencies.
Each component initialization should create independent state unless you choose to clone/share a handle. The playground composable shows a complete implementation.
Know the boundaries
Computed reports cycles or concurrent evaluation through ReactiveError. The current framework republishes descriptions rather than guaranteeing per-property native updates. A native repaint alone does not rerun application handlers or reconstruct component state.
For slow work, use background tasks. For state shared through a subtree, use dependency injection.
In a complete view value binding, <Text text={doubled} /> reads a Computed automatically. <Text text={counter.count} /> also works for a Signal stored inside a composable struct. This shorthand works with both automatic setup and <rust explicit> State fields; it does not change the normal Rust API inside handlers or getters.