Documentation / Fundamentals
Reactivity
Read and update reactive state, and share values throughout the view tree.
State
Mounted state is stored by name and type. Keep state declarations unconditional and their types stable. Bindings support set, update, set_if_changed, and field projections through map.
Read a binding through cx.read inside a view to establish a dependency. The runtime invalidates consumers of changed values. Derived::new tracks its own reads; Derived::distinct suppresses downstream updates when the derived result stays equal.
use refract::prelude::*;
struct Greeting;
impl View for Greeting {
fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
let name = cx.state("name", || String::from("World"));
Ok(v_stack()
.gap(8.0)
.child(text(format!("Hello, {}", cx.read(&name))))
.child(field(name).label("Name")))
}
}
fn greeting() -> impl View {
Greeting
}Environment
Typed environment keys define a Clone + PartialEq value and a default. Provide a local override with .environment::<Key>(value) and read it with cx.environment::<Key>(). The read becomes a reactive dependency.
use refract::prelude::*;
struct Accent;
impl EnvironmentKey for Accent {
type Value = Color;
fn default() -> Color {
Color::BLUE
}
}
struct AccentLabel;
impl View for AccentLabel {
fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
let accent = cx.environment::<Accent>();
Ok(text("A shared accent").foreground(accent))
}
}
fn themed_screen() -> impl View {
AccentLabel.environment::<Accent>(Color::rgb(30, 140, 160))
}Environment Object
For shared models, environment_object and cx.object() use pointer identity. Store observable model fields in graph state. Intermediate layout components do not need to forward the model as props.
Reading a model does not subscribe to every field automatically. Read its bindings through cx.read to track changes. A missing model provider produces a view error.
use refract::prelude::*;
use std::rc::Rc;
struct Profile {
name: Binding<String>,
}
struct ProfileName;
impl View for ProfileName {
fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
let profile = cx.object::<Profile>()?;
Ok(text(format!("Hello, {}", cx.read(&profile.name))))
}
}
fn profile_screen(model: Rc<Profile>) -> impl View {
ProfileName.environment_object(model)
}