# Reactivity

Read and update reactive state, and share values throughout the view tree.

<a id="bindings"></a>

## 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.

**Without macros (View trait)**

```rust
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
}
```

**With macros**

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

#[view]
fn greeting(cx: &mut ViewContext<'_>) -> impl View {
    #[state]
    let name: String = String::from("World");

    v_stack()
        .gap(8.0)
        .child(text(format!("Hello, {}", cx.read(&name))))
        .child(field(name).label("Name"))
}
```

<a id="environment"></a>

## 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.

**Without macros (View trait)**

```rust
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))
}
```

**With macros**

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

struct Accent;

impl EnvironmentKey for Accent {
    type Value = Color;

    fn default() -> Color {
        Color::BLUE
    }
}

#[view]
fn accent_label(cx: &mut ViewContext<'_>) -> impl View {
    #[environment(Accent)]
    let accent: Color;

    text("A shared accent").foreground(accent)
}

fn themed_screen() -> impl View {
    accent_label().environment::<Accent>(Color::rgb(30, 140, 160))
}
```

<a id="environment-object"></a>

## 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.

**Without macros (View trait)**

```rust
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)
}
```

**With macros**

```rust
use refract::prelude::*;
use std::rc::Rc;

struct Profile {
    name: Binding<String>,
}

#[view]
fn profile_name(cx: &mut ViewContext<'_>) -> impl View {
    #[environment_object]
    let profile: Rc<Profile>;

    text(format!("Hello, {}", cx.read(&profile.name)))
}

fn profile_screen(model: Rc<Profile>) -> impl View {
    profile_name().environment_object(model)
}
```

<a id="related-guides"></a>

## Identity and external work

State follows mounted identity. See [Views](/docs/views#identity) for keys and memoization. Use [Effects](/docs/effects) to own timers, subscriptions, and other resources with cleanup.

The [Macros](/docs/macros) reference covers the syntax of `#[state]`, `#[environment]`, and `#[environment_object]`. These attributes use the same runtime as `cx.state`, `cx.environment`, and `cx.object`.
