# Views

Compose typed views and preserve their mounted identities.

<a id="views"></a>

## Describe the interface

A view describes part of your interface. Compose primitives such as `view`, `text`, `h_stack`, and `v_stack` into a tree. Each `.child(...)` adds a child to its parent, and modifiers configure the view they are called on.

An ordinary Rust function can assemble and return a view tree. The example below places a title above a row of two labels. It has no state or event handlers; its content comes entirely from the values passed to the builders.

```rust
use refract::prelude::*;

fn welcome() -> impl View {
    v_stack()
        .gap(12.0)
        .child(text("Welcome"))
        .child(
            h_stack()
                .gap(8.0)
                .child(text("Rust views"))
                .child(text("Browser and desktop")),
        )
}
```

<a id="view-trait"></a>

## Implement the View trait

For a named component, define a struct for its inputs and implement `View::body`. The method borrows `self` and returns `Result<impl View, ViewError>`. Wrap the child tree in `Ok(...)`; use `?` when constructing it can fail.

Here, `name` is an ordinary owned input. The view context is unused because this component only formats its input. Construct `Greeting { name: ... }` wherever a view is accepted, including in another view's `.child(...)` call.

```rust
use refract::prelude::*;

struct Greeting {
    name: String,
}

impl View for Greeting {
    fn body(&self, _cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        Ok(v_stack()
            .gap(8.0)
            .child(text("Welcome"))
            .child(text(format!("Hello, {}!", self.name))))
    }
}

fn application() -> impl View {
    Greeting { name: "Ada".into() }
}
```

<a id="view-fn"></a>

## Use a view_fn closure

`view_fn` creates a view from a closure with the same context and result shape as `View::body`. Use it for a small component or an inline view that captures owned values without defining a named struct.

The closure must implement `Fn(&mut ViewContext<'_>) -> Result<V, ViewError>` for a view type `V`, and its captures must be `'static`. Use `move` to own captures such as `String`. The runtime may call the closure again, so borrow or clone captured values rather than consuming them. Keep view construction free of side effects.

```rust
use refract::prelude::*;

fn greeting(name: String) -> impl View {
    view_fn(move |_cx| {
        Ok(v_stack()
            .gap(8.0)
            .child(text("Welcome"))
            .child(text(format!("Hello, {name}!"))))
    })
}

fn application() -> impl View {
    greeting("Ada".into())
}
```

<a id="view-macro"></a>

## Declare a view with #[view]

`#[view]` turns a function into a view constructor. Its first argument is `&mut ViewContext<'_>`; later arguments are owned inputs. Call the generated constructor with those inputs only: the runtime supplies the context when it evaluates the view.

A function returning `impl View` can return the child tree directly. For fallible construction, use `Result<impl View, ViewError>` and propagate errors with `?`. The `macros` Cargo feature is enabled by default; import `refract::prelude::*` to bring the attribute into scope.

All three forms compose with the same primitives and modifiers. Choose a struct for an explicit named type, a closure for captured inputs, or the macro for function-style declarations. The [Macros guide](/docs/macros#view) covers the attribute's full signature rules.

```rust
use refract::prelude::*;

#[view]
fn greeting(_cx: &mut ViewContext<'_>, name: String) -> impl View {
    v_stack()
        .gap(8.0)
        .child(text("Welcome"))
        .child(text(format!("Hello, {name}!")))
}

fn application() -> impl View {
    greeting("Ada".into())
}
```

<a id="identity"></a>

## Keep identity stable

Use `.key(item.id)` on reorderable children. Keys are sibling-local strings obtained through `ToString`. Moving a keyed child preserves its mounted identity; changing that identity resets local state.

Use `.memo(props)` to preserve a subtree across new parent descriptions when its explicit props and provider scope match. Reactive dependencies still update. Include every nonreactive input and callback capture that affects the output in those props.

```rust
text("A stable item")
    .key("item-42")
```
