- Docs
- Components
State and effects
A component function runs once. Whatever can change (a text, an attribute, a block or an effect) is a small lambda that runs again when the state it read changes, and only then:
State
State is explicit: var x by state(initial) declares a reactive variable, and the markup, derived blocks and effects that read it update when it changes. Writing a value equal to the current one does nothing, so to change a list you assign a new one (items = items + item).
A var by state that nothing assigns, increments, binds or fills with @ref never changes, and the compiler says that a plain val is enough.
Derived values
A value computed from state is declared with by derived { }. It follows whatever its block reads, directly or through a function. A plain val is computed once, when the component is created, and the compiler warns when it reads state or a prop.
A derived value computes when something reads it and one of its sources changed, and its readers only run again when the result differs. A computation that throws throws to whatever reads the value, and runs again once one of its sources changes.
Writable derived values
A var by derived can be written, and binds like state. What is written stays until one of the values the block read changes, then the block computes the value again:
During static rendering, which can't tell what changed, a written value holds while the block still computes what it computed at the write.
Shared state
state and derived work in any .kt file too, at the top level or in a class or an object, which is how components share state:
A top-level derived is created by the first component that reads it, and keeps following its sources while something reads it. The JVM renders pages on the same declarations, so a shared state written during static rendering is visible to the other renders of the process.
Effects
mount { } runs once in the browser, after the component is hydrated or created. effect { } runs in the browser after the first render, and again each time a state, derived value or prop it read changes. Neither runs during static rendering, so code that needs the DOM or browser APIs goes there.
onDispose { } registers a cleanup, in mount, effect and @mount: it runs when the component or the element leaves the page, and in an effect also before its next run.
import web.dom.document
import web.resize.ResizeObserver
import web.timers.clearTimeout
import web.timers.setTimeout
prop val pageSize: Int
var query by state("")
var width by state(0)
var results by state(emptyList<Result>())
mount {
val observer = ResizeObserver { entries, _ -> width = entries[0].contentRect.width.toInt() }
observer.observe(document.body)
onDispose { observer.disconnect() }
}
effect {
val text = query // the effect runs again when `query` changes
val limit = untracked { pageSize } // and not when `pageSize` does
val timer = setTimeout({ results = search(text, limit) }, 200)
onDispose { clearTimeout(timer) }
}
An effect follows what it reads while it runs. A value only read in a callback that runs later, like a timer's, doesn't make it run again, and the compiler warns about it. untracked { } reads a value without following it.
This stopwatch starts an interval in an effect that reads running. The cleanup stops it when the watch stops or the component leaves:
<script kotlin>
import web.timers.clearInterval
import web.timers.setInterval
import kotlin.time.TimeSource
var running by state(false)
var elapsed by state(0)
effect {
if (!running) return@effect
val base = untracked { elapsed }
val start = TimeSource.Monotonic.markNow()
val timer = setInterval({ elapsed = base + start.elapsedNow().inWholeMilliseconds.toInt() }, 31)
onDispose { clearInterval(timer) }
}
</script>
<output>{elapsed} ms</output>
<button type="button" @click={running = !running}>{if (running) "Stop" else "Start"}</button>
When things run
- Writes are batched. State writes are applied in a microtask, so all the writes of one handler update the DOM once, before the next paint.
- Outer first. Effects run in the order they were created, so a block runs before what it contains: a branch that disappears is removed before its content reads state that no longer holds.
mountandeffectblocks run after the DOM updates of the same pass. - Scopes. Effects, derived values and cleanups belong to the scope that created them: the component, a branch of an
@if, the content of a@key, or an item of a@for. Leaving the page disposes the scope, which stops its effects and runs its cleanups. - Failures stay local. A block that throws doesn't stop the others, and the first failure is thrown at the end of the pass. A text, an attribute, a branch or a list that throws the first time it runs keeps its place in the page, what follows it is built, and it runs again when the state it read changes. Error boundaries show a fallback in its place.
- No endless loops. An effect that keeps writing the state it reads fails after 1000 rounds, with
An effect keeps changing the state it reads.
Browser APIs and static rendering
Browser APIs come from kotlin-browser (web.* packages) and are imported like any Kotlin declaration. Static rendering has no browser, so the compiler leaves out of it mount, effect, onDispose, element listeners, @ref, @mount, and every statement of the script that uses a browser API, directly or through another statement left out. Nothing needs to be marked. Markup that needs one of these at build time is a compile error:
import web.storage.localStorage
fun save() = localStorage.setItem("draft", draft) // browser only, call it from a handler, `mount` or `effect`
- A browser API is a name imported from
web.*,js.*,org.w3c.*,kotlinx.browser.*,kotlinx.dom.*,kotlin.js.*,seskar.*,org.jetbrains.compose.web.*orio.github.ayfri.lithe.compose.*, a global of Kotlin/JS (console,js,Date,Promise,JSON,jsTypeOf,undefined) or a fully qualifiedweb.name. - A star import of such a package is an error, because the compiler can't tell which names it brings.
- A prop whose type or default uses a browser API is an error.
- The compiler reads one file at a time, so a helper declared in a
src@jsKotlin file isn't recognized: the Kotlin compiler reports its use in static code.