# Signals & Reactivity (https://crow.build/docs/core/reactivity)

`crow-signals` is Crow's platform-free reactive kernel (inspired by SolidJS 2.0 and verified by a 100,000-seed differential fuzzer). Every piece of dynamic UI, async data, styling, and animation in Crow builds on four primitives: **signals**, **derived values**, **effects**, and **owners**.

## Signals [#signals]

Create local or shared reactive state with `signal(initial)`. In a `@Ui` function, top-level `var x by signal(init)` declarations are compiled by K2 into fields of a single generated `LocalGraph` class — zero per-signal heap overhead.

```kotlin
@Ui
fun LikeRow(title: String, @Once initialCount: Int, avatar: Int) {
    var liked by signal(false)
    var count by signal(initialCount)

    Row(
        Modifier
            .fillMaxWidth()
            .clickable { count++ }
            .padding(horizontal = 16.dp, vertical = 8.dp),
    ) {
        Box(Modifier.size(40.dp).background(avatar, CircleShape))
        Column(Modifier.weight(1f).padding(start = 12.dp)) {
            Text(title)
            Text("$count likes")
        }
        Box(
            Modifier.size(48.dp).clickable { liked = !liked },
            contentAlignment = Alignment.Center,
        ) {
            Box(Modifier.size(24.dp).background(if (liked) LikedRed else Gray, CircleShape))
        }
    }
}
```

### Equality & Lanes [#equality--lanes]

- **Structural equality by default**: `signal(value, equality = Equality.Structural)` compares with `==` and short-circuits downstream work when values are equal. Use `Equality.Referential` (`===`) or `Equality.Never` when needed.
- **Synchronous reads, batched reactions**: Writing `count++` updates the value immediately — reading `count` or any derived value on the next line returns the new value. UI bindings and effects run in a coalesced `flush()`.
- **Lanes**: Signals default to `Lane.Default` (they participate in held async transitions). Direct-manipulation state (text carets, gestures, springs) uses `Lane.Immediate`, so typing or dragging never stalls while async data loads.

## Derived Values [#derived-values]

Compute memoized values with `val x by { ... }` (delegating to `derived { ... }`):

```kotlin
var price by signal(24.0)
var quantity by signal(2)

val subtotal by { price * quantity }
val formatted by { "$${"%.2f".format(subtotal)}" }
```

Derived values pull lazily when read, cache their output, and only notify downstream bindings when their result actually changes (structural equality). Pass `derived(lazy = true) { ... }` when you want a computation to detach while unobserved.

## Split Effects & Reactions [#split-effects--reactions]

Side effects in Crow are **split into two lambdas**: `track` (pure reads that declare dependencies) and `run` (untracked body that receives `(value, previous)` and may register cleanups or write signals):

```kotlin
effect(track = { userId }) { id, prevId ->
    val subscription = analytics.observeUser(id)
    onCleanup { subscription.close() }
}
```

| Primitive | When it runs | Typical use |
| --- | --- | --- |
| `effect(track) { v, prev -> }` | After flush settles, deferred while owner is dormant | Analytics, listeners, external I/O |
| `renderEffect(track) { v, prev -> }` | Immediately at mount and before user effects | Internal UI bindings and host sync |
| `reaction(onInvalidate)` | On-demand tracking via `Reaction.track { }` | Custom `Canvas` / `drawBehind` invalidation |
| `onSettled { }` | Once after the current flush settles | Post-commit callbacks |

## Owners & Lifetime [#owners--lifetime]

Every `setContent`, reactive `if`/`when` branch, `For` item, `LazyColumn` row, `Overlay`, and `NavHost` entry creates an **`Owner`**.

- Effects, resources, and `onCleanup { }` callbacks automatically bind to the active owner.
- When a branch leaves or a screen pops, its owner disposes children first, then runs cleanups in LIFO order.
- Dormant owners (such as a covered screen in `BackStack` `keepAlive`) defer user effects until the screen returns to the foreground, while keeping bindings intact.
- Outside UI code, create owners manually with `root { dispose -> ... }` or `detachedRoot { dispose -> ... }`.

## Compile-Time Guards (`CR1001`, `CR1002` & `CR1003`) [#compile-time-guards-cr1001-cr1002--cr1003]

Crow's K2 FIR checkers eliminate the classic fine-grained reactivity footguns before your app even compiles:

- **`CR1001` — Frozen reactive read**: Reading a signal, `Resource`, `Animatable`, or live prop inside a plain `val` in a `@Ui` body is a compile error. Fix it with `val x by { ... }` (reactive) or `untrack { ... }` (explicit one-time snapshot).
- **`CR1002` — Write during UI build**: Mutating a signal directly inside a `@Ui` body is rejected at compile time. Perform writes in click handlers, `effect` bodies, or coroutines on `Dispatchers.Crow`.
- **`CR1003` — `@Ui` lambda in class field**: Storing a `@Ui () -> Unit` function type in a class property or constructor parameter is rejected at compile time. Pass `@Ui` lambdas as parameters to `@Ui` functions instead.