Views and Composition
Build reusable interfaces with owned descriptions and small, composable units.
Composition lets you give a meaningful part of an interface its own inputs and state ownership. In Hera Kit, that part can be expressed as an ordinary function, a closure view, a function annotated with the view macro, or a named type. The choice depends on whether it only arranges supplied data or also needs access to mounted state and inherited values.
Functions with Supplied Data
use hera_kit::{h_stack, spacer, text, View};
fn summary(title: String, remaining: usize) -> impl View {
h_stack()
.spacing(12.0)
.child(text(title))
.child(spacer())
.child(text(format!("{remaining} remaining")))
}The summary function needs only the title and count supplied by its caller, so an ordinary function is enough. It returns a composed description without accessing a view context, because it neither owns mounted state nor reads the environment.
Local Bodies with view_fn
When a small piece of composition needs mounted state or inherited values, use view_fn to give its body a ViewContext. The closure returns an owned description in a Result, allowing evaluation errors to propagate through the same path as a named view.
use hera_kit::{button, text, view_fn};
let counter = view_fn(|cx| {
let count = cx.state("count", || 0u32);
let value = cx.read(&count);
Ok(button(text(format!("Count: {value}")), move |ctx| {
count.update(ctx.runtime, |value| *value += 1);
}))
});The toolkit may invoke this closure again after state changes, so its returned description must own the values it needs. Clone an owned prop before moving it into that description, and clone a binding when several children or actions need shared access to it.
Named View Types
Use a named type when the view represents an application concept such as a screen or reusable control. The struct holds its props, while View::body(&self, cx) obtains mounted state from the context and returns Result<impl View, ViewError>. This keeps construction separate from evaluation and lets missing-model or other evaluation errors propagate normally.
The following Counter struct composes a title and a button into a reusable control. Its fields describe the inputs, while the count itself belongs to the mounted view context.
use hera_kit::{button, text, v_stack, View, ViewContext, ViewError, ViewExt};
struct Counter {
title: String,
initial: u32,
}
impl View for Counter {
fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
let count = cx.state("count", || self.initial);
let value = cx.read(&count);
Ok(v_stack()
.spacing(8.0)
.child(text(self.title.clone()))
.child(button(text(format!("Count: {value}")), move |ctx| {
count.update(ctx.runtime, |value| *value += 1);
})))
}
}
let content = v_stack()
.spacing(24.0)
.child(
Counter {
title: "Completed tasks".into(),
initial: 0,
}
.key("completed"),
)
.child(
Counter {
title: "Planned tasks".into(),
initial: 10,
}
.key("planned"),
);Constructing a Counter supplies its props without creating its state. During evaluation, cx.state creates the "count" slot on the first mount and reuses it on later evaluations. Changing initial at an existing identity does not reset that slot.
The returned description owns a clone of the title and moves the count binding into the button's action, allowing both to outlive the call to body without borrowing self. The body can therefore describe the current state through &self, while the action changes mounted state through its runtime context. Each keyed instance owns its state independently and retains its identity if its sibling order changes.
Application views implement body. The hidden build hook and raw UiNode construction belong to backend primitives and specialized host code.
Macro-Authored Views
The #[view] macro lets you write a reusable, stateful view as a function while declaring its state and action captures alongside its composition. The following example expresses the same counter as the struct above: each mounted counter owns its count, while its caller supplies a title and an initial value.
use hera_kit::{button, text, v_stack, view, View, ViewContext, ViewExt};
#[view]
fn counter(cx: &mut ViewContext<'_>, title: String, initial: u32) -> impl View {
#[state]
let count: u32 = initial;
#[action(count)]
let increment = |ctx| {
count.update(ctx.runtime, |value| *value += 1);
};
v_stack()
.spacing(8.0)
.child(text(title))
.child(button(
text(format!("Count: {}", cx.read(&count))),
increment,
))
}
let content = v_stack()
.spacing(24.0)
.child(counter("Completed tasks".into(), 0).key("completed"))
.child(counter("Planned tasks".into(), 10).key("planned"));The runtime supplies cx when it evaluates the body, so callers pass only the title and initial value. The macro turns the #[state] declaration into a binding to mounted state, and #[action(count)] clones that binding into the button's action. Reading the binding with cx.read makes the displayed count depend on that state; pressing the button updates it through the action's runtime context.
Each counter has its own mounted identity and therefore its own state. The initial value is used when that identity first mounts, so rebuilding the parent description does not reset either count. The keys distinguish the counters within their parent and preserve their identities if their sibling order changes.
The macro is available through Hera Kit's default macros feature and generates an ordinary closure view with the same evaluation and ownership rules as view_fn. See attribute view authoring for inherited dependencies, explicit state slot IDs, and fallible bodies.
Child Composition and Identity
Containers accept .child(view), .children(iterator), and .maybe_child(option). An iterator's items have one concrete view type; compose heterogeneous fixed content with successive .child calls.
For a fixed hierarchy, a child's structural position and concrete view type supply its state identity. If siblings can reorder, give them stable keys through .key(item_id) so their state follows the item within that parent. A key remains scoped to its parent rather than acting as a global storage location.
Read identity before adding conditional stateful branches or changing wrapper structure. Read modifiers to understand how wrappers affect layout and appearance.
Source Reference
The following files in the Hera checkout define the behavior described on this page.
crates/kit/src/view/mod.rscrates/kit/src/view/context.rscrates/kit/src/view/primitives.rscrates/kit/docs/ATTRIBUTES.mdcrates/kit-macros/src/lib.rs