GUIDE / ADVANCED INTERFACE

Reactivity in depth

Exactly when state notifies, who owns a reactive collection, and how to group or hide reads.

Core janelkit Included with janelkit. Nothing extra to install.
CHAPTER 25 / 29~3 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

  • Who owns a reactive collection and why the original is not updated.
  • When an assignment notifies and when it does not.
  • How to group writes with batch and read without subscribing with peek and untracked.
  • How objects with state attributes and @computed methods behave in templates.

Mutate the reactive collection, not its input

Built-in lists, dictionaries and sets become reactive containers when stored in state, including nested ones and new ones inserted later. They remain subclasses of list, dict and set, so append, remove, sort, item assignment, deletion and set operations update the interface without replacing the whole value.

Conversion copies the containers. The list you passed to state is not the list the state now owns. Change data through items.value, or through a row obtained from it. Each collection notifies separately: editing one task dictionary updates what reads that dictionary, not every reader of the outer list.

Tuples, your own subclasses of collections and other objects are not converted. Prefer replacing such a value. If you change one in place on purpose, call the state’s notify() afterwards.

python
# Ordinary Python: who owns the data after state() copies it.
from janelkit import state

original = [{"title": "First", "done": False}]
todos = state(original)

original[0]["done"] = True          # edits the original, not the reactive copy
assert todos.value[0]["done"] is False

todos.value[0]["done"] = True       # edits the reactive copy: readers update
assert todos.value[0]["done"] is True
Copy

What you should see

Running the snippet prints nothing: both assertions pass, showing that only changes through todos.value reach the reactive copy.

Common mistakes

  • Changing an attribute of a custom object is not observable. Replace the value, or call notify().

When an assignment notifies

Assigning a value equal to the current one, of the same type, is ignored: nothing updates. Assigning the very same object again is also ignored, so it cannot replace notify() after an in-place change. Values of different types count as a change even when they compare equal, such as 1 and True.

A binding subscribes to the state it reads while it is evaluated, including reads made inside helper functions it calls. A plain read made earlier, before the binding existed, does not become a subscription.

Group related writes with batch

with batch(): delays observer work until the outermost batch ends. Assignments still happen at once, so Python code inside the block reads the new values; only the reaction waits. It is not a transaction: an error does not undo the writes.

Event handlers and timer callbacks are already batched. Use batch in shared functions that may run outside a handler. Do not hold a batch across await.

python
# Ordinary Python: the effect sees both names change together.
from janelkit import state, effect, batch

first = state("Ada")
last = state("Lovelace")
seen = []
watcher = effect(lambda: seen.append((first.value, last.value)))

with batch():
    first.value = "Grace"
    last.value = "Hopper"

assert seen == [("Ada", "Lovelace"), ("Grace", "Hopper")]
watcher.dispose()
Copy

How it works

  1. effect runs once immediately, recording ("Ada", "Lovelace").
  2. Without batch, it would also run between the two assignments and record ("Grace", "Lovelace").
  3. An effect created outside a component must be stopped with dispose().

Read without subscribing

state.peek() reads a value without subscribing to it. with untracked(): turns off tracking for every read in its block, including the contents of collections. Use them for incidental information, such as context added to a log line, that should not cause a rerun.

A reactive list returned by peek() is still reactive: calling len or iterating it outside untracked can subscribe again. Wrap the whole read in untracked.

python
# Ordinary Python: only request triggers the effect; notes is context.
from janelkit import state, effect, untracked

request = state(0)
notes = state(["draft"])
logs = []

def record():
    current = request.value
    with untracked():
        count = len(notes.value)
    logs.append((current, count))

watcher = effect(record)
notes.value.append("review")        # does not rerun record
request.value = 1                   # reruns record
assert logs == [(0, 1), (1, 2)]
watcher.dispose()
Copy

Common mistakes

  • peek and untracked do not freeze data, silence existing subscribers or allow writes from worker threads.

Objects with state of their own

Not all data is the application’s shared data. An object that exists several times, such as one Camera per camera or one Connection per server, can keep its own state as attributes. A template uses them directly: {camera.frames}, {#if hub.ready} and {#each hub.errors as e} show the value and update. Inside an operation, ask for the value: {camera.frames.value * 2}.

@computed on a method gives each instance its own computed, which lives as long as the instance: camera.health.value in Python, {camera.health} in the template.

python
# Ordinary Python: state attributes and a derived value per instance.
from janelkit import computed, state

class Camera:
    def __init__(self, name):
        self.name = name
        self.frames = state(0)
        self.dropped = state(0)

    @computed
    def health(self):
        total = self.frames.value + self.dropped.value
        return 1.0 if total == 0 else self.frames.value / total

front, back = Camera("front"), Camera("back")
front.frames.value = 9
front.dropped.value = 1
assert front.health.value == 0.9
assert back.health.value == 1.0     # each instance has its own computed
Copy

Common mistakes

  • For the data several views or windows share, prefer a store of janelkit-store: one instance per application, actions and a fresh instance in each test.

Learn morejanelkit-store ↗

Key points

  • state copies collections; change them through .value.
  • Equal values of the same type do not notify; call notify() after changing custom objects.
  • batch groups reactions; peek and untracked read without subscribing.
  • State attributes work in templates; @computed on a method gives each instance its own value.

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