GUIDE / FUNDAMENTALS

Computed values

Derive values from state instead of storing copies, and let JanelKit keep them correct.

Core janelkit Included with janelkit. Nothing extra to install.
CHAPTER 11 / 29~2 min read · try examples at your own pace
Alpha / 0.2 — These pages document JanelKit 0.2 and its packages. Each series (0.1, 0.2…) may change the public API, always with migration notes: see Changes and migration. The website uses Svelte; the desktop examples use Python and JanelKit, not JavaScript.

What you will learn

  • Why derived data should be computed, not stored.
  • How @computed tracks what it reads and caches its result.
  • When to use state, computed or an effect.

Calculate an answer instead of storing it

If a total is always price times quantity, storing it in a third state means remembering to update it every time either input changes. Sooner or later one place forgets. @computed expresses the relationship once: the function returns the answer, and JanelKit keeps it up to date.

The decorator turns the function into a Computed object. Read it like state: total.value in Python, total in the template. Do not call it and do not assign to it.

janel
<script lang="python">
from janelkit import state, computed

quantity = state(1)
price = state(12)

@computed
def total():
    return quantity.value * price.value
</script>

<window title="Computed" width={420} height={220}>
  <column padding={24} gap={12}>
    <text>{quantity} × {price} credits = {total} credits</text>
    <button on:click={quantity += 1}>Add one</button>
    <button on:click={price = 10}>Discount</button>
  </column>
</window>
Copy

Complete component · Save as src/App.janel in a scaffolded project.

How it works

  1. quantity and price are the source of truth; total is read-only derived data.
  2. Inside the function, read inputs with .value, as in any Python code.
  3. In the template, {total} shows the current answer.

What you should see

1 × 12 credits = 12 credits at first. Add one shows 2 × 12 credits = 24 credits. Discount then shows 2 × 10 credits = 20 credits.

It follows what it actually reads

You do not declare dependencies. While the function runs, JanelKit records which state it reads; when any of those changes, the cached result is marked stale and recalculated the next time someone reads it. Each run records its dependencies again, so a condition decides what matters: below, while show_net is False, changes to net are ignored.

python
# Ordinary Python: the branch taken decides the dependencies.
from janelkit import state, computed

show_net = state(False)
gross = state(120)
net = state(100)

@computed
def displayed():
    return net.value if show_net.value else gross.value

assert displayed.value == 120
show_net.value = True
assert displayed.value == 100
Copy

How it works

  1. Computed values are lazy: they calculate on first read, not on creation.
  2. They are cached: reading them twice without changes does not recalculate.
  3. When a recalculated number, string or tuple equals the previous one, the bindings that read it are not updated.

Keep computed functions pure

A computed function should only calculate and return. It must be synchronous and must not change state, start timers, write files or call web services. Those are actions, not answers, and belong in event handlers, effects or async tasks.

Common mistakes

  • Do not write state inside a computed function; that creates loops and surprises.
  • Returning the same list object does not prove its contents are unchanged; prefer returning new values.
  • total() is an error: total is a Computed object, read total.value.

state, computed or effect?

Three tools look similar but answer different questions. Ask what the value is for.

QuestionToolExample
Is it data the user or the program sets?stateThe text typed in a field, the selected item.
Can it be calculated from other data?computedA total, a filtered list, a count of pending tasks.
Must something happen outside when data changes?effectLog a change, save a preference, sync with a service.

Learn moreLifecycle and effects ↗Reactivity in depth ↗

Practice: a filtered list

Combine a list in state, a search text bound to a <textfield>, and a computed that returns only the items containing the search text. Show the computed list with {#each} and its length in a <text>. The filtered list is never stored: it is always calculated from the two inputs.

Common mistakes

  • Do not keep a second filtered list in state and update it by hand; that is exactly what computed replaces.

Key points

  • @computed derives a value from state; read it with .value or by name in the template.
  • It tracks what it reads, calculates lazily and caches the result.
  • Keep it pure: calculations only, no side effects.

English documentation based on the JanelKit source. For additional details, browse the source docs ↗.