---
title: .derived()
description: Tutorial — compute values from state automatically with the .derived() builder method.
order: 103
---

import { Preview } from "$lib/components/preview";

export const example = `import ilha from "ilha";
import { Button } from "areia";

export default ilha
  .state("count", 1)
  .derived("doubled", ({ state }) => state.count() * 2)
  .on("[data-action=increase]@click", ({ state }) => {
    state.count(state.count() + 1);
  })
  .render(({ state, derived }) => (
    <>
      <p>Count: {state.count()}</p>
      <p>Doubled: {derived.doubled()}</p>
      <Button variant="primary" data-action="increase">
        Increase
      </Button>
    </>
  ));
`

# Derived

Now that you can mutate state with `.on()`, derived properties let you compute
values from that state automatically — recalculating only when their dependencies
change. Use `.derived()` to keep complex logic out of your templates and make
components easier to reason about.

```ts
.derived("name", ({ state }) => /* computed value */)
```

The callback receives the component context, just like `.on()`. The result is
available in `.render()` via `derived.name()` — the same call syntax as state.

You can also write `derived.name(value)` for optimistic UI; the next time the
derived function runs, it overwrites with the computed result.

`.derived()` also accepts an async function, making it suitable for data fetching.
Async derived values expose `loading`, `value`, and `error` on the accessor — so
you get built-in async state without reaching for SWR or TanStack Query.

<Preview code={example} size="lg" />

## Similar concepts

- React: `useMemo`
- Vue: `computed()`
- Svelte: `$derived()`
