# Effects

Tie external work to mounted lifetimes with explicit dependencies and cleanup.

<a id="effects"></a>

## Own work with an effect

An effect starts after a successful commit and returns a cleanup closure. Changed dependencies and committed unmounts clean up the previous effect. Discarded candidates never start effects.

Inside a `#[view]` function, `#[effect]` declares this lifecycle. In the clock example, the injected `subscribe` function owns the platform timer and returns its cleanup.

```rust
#[effect(id = "one-second-clock", captures(subscribe, reading, scope))]
let clock_timer = |_| {
    subscribe(reading.clone(), scope.clone())
};
```

> This is an excerpt from the clock pattern, not a standalone function. Effects must be unconditional top-level declarations, with unique IDs within the view.

<a id="dependencies"></a>

## Make dependencies explicit

Effect dependencies default to `()`, so setup runs once per mounted identity. Add `deps = period` or `deps = (period, enabled)` to restart when those values change according to `PartialEq`.

Reads inside setup do not establish view dependencies. Read reactive values during view evaluation and include inputs that should restart setup explicitly. `captures(...)` clones handles for the closure; it does not infer dependencies.

Use [Channels](/docs/channels) to deliver async and background results into reactive state. Keeping the subscription in effect cleanup rejects late results after dependency replacement or unmount. Scoped update handles also discard queued completions after their owning view unmounts.

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

## State and effect declarations

Read [Reactivity](/docs/reactivity) for reactive bindings and shared models. The [effect macro reference](/docs/macros#effect) documents declaration syntax; handwritten views register effects through `cx.effect`.
