GUIDE / BUILDING APPLICATIONS

Lifecycle and effects

What happens when a component is created, shown, updated and removed, how to run code at each moment, and who cleans up.

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

  • The moments in a component’s life and what to do in each.
  • How on_mount, on_destroy and cleanup functions work.
  • How effects react to changes, and how to stop them.
  • Which work stops on its own when a component is removed.

Four moments in a component’s life

Setup runs the script: state, functions and registrations are created. Mount happens when the view exists, so controls can be focused. Updates happen many times while the instance lives; they never run the script again. Destroy happens when the instance is removed: an {#if} branch closes, a list row is deleted, a page is discarded, the application closes.

MomentHappensDo here
SetupOnce, when the instance is createdCreate state, define functions, register hooks.
MountOnce, when the view existsFocus a field, measure, start work that needs the view.
UpdateEvery time read data changesNothing by hand: bindings and effects react.
DestroyOnce, when the instance is removedRelease what you started: connections, subscriptions.

Register hooks while the script runs

on_mount(fn), on_destroy(fn) and before_leave(fn) register a function for the current component; each also works as a decorator. Registration must happen while the script runs, at the top level or in a helper called from it. The same rule applies to provide, inject and is_visible, and to the page stacks of janelkit-router. A later button click is too late: calling them from a handler raises RuntimeError.

Common mistakes

  • Do not call on_destroy inside a click handler to attach cleanup after an operation. Register it during setup.

on_mount: when the view exists

During setup the controls do not exist yet. on_mount runs once, after the component’s view and its children’s views exist; children mount before their parent. If the function returns another function, that one is a cleanup that runs when the component is destroyed. Return the function itself, not the result of calling it.

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

name = state("Ada")
field = ref()

@on_mount
def prepare():
    field.focus()
    field.select_all()
    print("mounted")
    return lambda: print("mount cleanup")
</script>

<column padding={24} gap={12}>
  <textfield ref={field} bind:value={name} label="Name" />
  <text>Hello, {name}</text>
</column>
Copy

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

How it works

  1. ref() creates a handle; ref={field} attaches it to the <textfield> when the field exists.
  2. In on_mount the field exists, so focus() and select_all() act on it.
  3. The returned lambda is stored and called when the component is destroyed.

What you should see

The window opens with the name selected and ready to be replaced, and prints mounted. Closing it prints mount cleanup.

Learn moreRefs: control an element from code ↗

on_destroy, and the order of cleanups

on_destroy(fn) runs fn when the component is destroyed. Cleanups run in the reverse order of registration: the last thing registered is released first. on_destroy registers during setup; an effect registers when it is created; a mount cleanup registers later, when on_mount runs. So in the example below the mount cleanup runs first and the destroy callback last.

janel
<script lang="python">
from janelkit import on_destroy, effect, on_mount

on_destroy(lambda: print("destroy callback"))

def observe():
    return lambda: print("effect cleanup")
effect(observe)

@on_mount
def mounted():
    return lambda: print("mount cleanup")
</script>

<text>Close the window to see the cleanup order.</text>
Copy

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

What you should see

Closing the window prints mount cleanup, then effect cleanup, then destroy callback.

Common mistakes

  • Destroy callbacks are not awaited. Do not rely on an async on_destroy to finish saving data.
  • Write each cleanup so it releases only its own resource, without depending on the order of others.

Effects: do something when data changes

An effect is for acting outside the interface when data changes: logging, saving a preference, keeping a connection in sync. It is not for calculating a value; use computed for that. effect(fn) runs fn at once and records the state it reads; whenever one of those changes, it runs fn again. If fn returns a function, that is its cleanup, called before the next run and when the effect ends.

An effect created in a component ends with the component. You can end it earlier with dispose() on the object effect returns. An effect created in an ordinary module, outside any component, has no owner: keep it and call dispose() yourself.

janel
<script lang="python">
from janelkit import state, effect
channel = state("news")

def watch_channel():
    name = channel.value
    print("Start", name)
    return lambda: print("Stop", name)

watcher = effect(watch_channel)

def stop_watching():
    watcher.dispose()
</script>

<column padding={24} gap={12}>
  <text>Channel: {channel}</text>
  <button on:click={channel = "sports"}>Choose sports</button>
  <button on:click={stop_watching}>Stop watching</button>
</column>
Copy

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

How it works

  1. The effect reads channel, so it reruns whenever channel changes.
  2. The returned lambda remembers the name of the run that created it, so it stops the right channel.
  3. watcher.dispose() ends the effect early; the label keeps updating because it is a binding, not part of the effect.

What you should see

Setup prints Start news. Choosing sports prints Stop news, then Start sports. Stop watching prints Stop sports; the label still changes, but the effect no longer runs.

Common mistakes

  • Do not write a state that the same effect reads and changes every time: that is an endless loop.
  • Only reads made while fn runs synchronously count. Reads after an await are not tracked.

Learn moreComputed values ↗Reactivity in depth ↗

What stops on its own

Work started by a component belongs to it and is released when it is destroyed. A list row releases its own work when the row is deleted. Only resources that JanelKit does not know about, such as a socket or a file you opened yourself, need an explicit cleanup.

Started in a componentWhen the component is destroyed
effect(...)Disposed; its last cleanup runs.
@task, spawn(...), async handlersCancelled.
interval(...), timeout(...)Stopped.
open_window(...)The window closes.
A connection or file you openedNothing: release it in on_destroy or in a cleanup.

Common mistakes

  • Hiding is not destroying. Content inside {#hidden}, a list row scrolled out of view, and a covered page or inactive section of janelkit-router stay alive. What they show waits and catches up when they are seen again, but their effects, timers and tasks keep running. is_visible() tells a component whether it is seen; see Timers.
  • before_leave asks permission to close a window or leave a page; it is not a cleanup hook. Release resources in on_destroy.

Learn moreAsync work ↗Timers ↗Windows and screens ↗

Key points

  • Setup runs once; mount happens when the view exists; destroy releases the instance.
  • Register hooks during setup; cleanups run in reverse order of registration.
  • Effects react to the state they read; work started in a component stops with it.

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