Rook source
comp Counter() {
state count = 0
return <main>
<button onClick={count++}>{count}</button>
<p>{count * 2}</p>
<small>{"always here"}</small>
</main>
}
document.body.append(<Counter />)
Nothing found.
Change a value and follow the pulse through its dependency graph. Only the DOM nodes that read it update; the independent label stays still.
Ready · count = 0
comp Counter() {
state count = 0
return <main>
<button onClick={count++}>{count}</button>
<p>{count * 2}</p>
<small>{"always here"}</small>
</main>
}
document.body.append(<Counter />)
updated nodes flash
0
always herestate declares a variable that the markup depends on. The compiler knows which parts of the markup read it and where it changes, and after each change it updates exactly those parts. There are no subscriptions and no DOM diffing, as the JavaScript tab shows.
// state is a variable that the markup depends on. After count++ the compiler // updates the button's text by itself: no virtual DOM and no library comp Counter(start number) { state count = start return <button onClick={count++}>Clicked {count} times</button> } document.body.append(<Counter start={0} />)
bind:value and bind:checked bind an input to state both ways.
// bind: binds an input to state both ways comp Greeting() { state name = "" state loud = false return <div> <input bind:value={name} placeholder="Your name" /> <label><input type="checkbox" bind:checked={loud} /> loud</label> <p>Hello, {name == "" ? "stranger" : name}{loud ? "!!!" : "."}</p> </div> } document.body.append(<Greeting />)
{if ...} and {for ...} update too. A branch is created again only when the condition changes, and the blocks of a list are found by the array item itself and moved, not created again.
The task list is now the board's first working version: adding or removing a task changes the list, and its empty state follows the same data. The example below is that small app.
type Filter "all" | "open" | "done" type Priority "low" | "normal" | "high" interface Task { id number title string done bool priority Priority } comp TaskBoard() { state tasks Task[] = [ { id: 1, title: "Define the task model", done: true, priority: "normal" }, { id: 2, title: "Build the task board", done: false, priority: "high" }, ] state title = "" state filter Filter = "open" state nextId = 3 func add() { if const trimmed = title.trim(); trimmed != "" { tasks.push({ id: nextId, title: trimmed, done: false, priority: "normal" }) nextId++ title = "" } } return <section> <form onSubmit={event.preventDefault(); add()}> <input bind:value={title} placeholder="New task" /> <button>Add task</button> </form> <nav aria-label="Filter tasks"> <button type="button" onClick={filter = "all"}>All</button> <button type="button" onClick={filter = "open"}>Open</button> <button type="button" onClick={filter = "done"}>Done</button> </nav> <p>{tasks.filter(task => !task.done).length} open tasks</p> <ul>{for task in tasks with key task.id { if filter == "all" || (filter == "open" && !task.done) || (filter == "done" && task.done) { <li> <label> <input type="checkbox" checked={task.done} onChange={task.done = !task.done} /> {task.title} </label> <small>{task.priority}</small> </li> } }}</ul> </section> } document.body.append(<TaskBoard />)
A list that comes again as new objects with the same data, as one loaded again from a server, has no item that stays, so all its blocks are made again and the components in them lose their state. with key fruit.id after the items finds the blocks by the key instead, a string or a number: star a fruit in both lists, then load them again.
// A list loaded from a server comes as new objects every time. Without // a key, its blocks are found by the item itself, so they are all made // again and lose their state; with key fruit.id they stay interface Fruit { id number name string stock number } // A pretend server: the same fruits with fresh stock, as new objects func load() Fruit[] { return ["Guava", "Lychee", "Mango"].map((name, i) => ({ id: i + 1, name, stock: Math.round(Math.random() * 9), })) } // Whether it is starred is state of its own, which a new block loses comp Row(name string, stock number) { state starred = false return <li> <button onClick={starred = !starred}>{starred ? "★" : "☆"}</button> {name}: {stock} in stock </li> } comp Shop() { state fruits = load() return <div> <button onClick={fruits = load()}>Load again</button> <p>Without a key:</p> <ul>{for fruit in fruits { <Row name={fruit.name} stock={fruit.stock} /> }}</ul> <p>With key fruit.id:</p> <ul>{for fruit in fruits with key fruit.id { <Row name={fruit.name} stock={fruit.stock} /> }}</ul> </div> } document.body.append(<Shop />)
derived declares a value computed from state, read-only. When the state changes, the value is computed again right before the markup that reads it is updated. A value that takes several statements is a block that returns it: derived note { ...; return text }. effect runs its code once the markup is created, and again when what it reads changes; it cleans up with defer, which runs before the effect runs again and when the component is removed.
// derived is a value computed from state: it is computed again when the state changes, // before the markup that reads it is updated comp Basket() { state prices number[] = [3, 2] derived total = prices.reduce((sum, price) => sum + price, 0) // A block computes it in several steps and returns the value derived note { const room = 10 - total if room <= 0 { return "That is a lot of guavas" } return `There is room for ${room} more` } // effect runs once the markup is created, and again when what it reads changes effect { console.log("total:", total) } return <div> <button onClick={prices.push(3)}>Add a guava</button> <p>{prices.length} fruits for {total}. {note}</p> </div> } document.body.append(<Basket />)
State that several components need is a state at the top level of a module. The components that read it are updated when it changes anywhere in the module: in a function, a handler or a timer. Other modules import it and read it, and change it with the functions of its module: items.push(x) there is an error that says so.
// State at the top level of a module is shared by its components: // a change anywhere in the module updates every component that reads it state cart string[] = [] func add(fruit string) { cart.push(fruit) } comp Shelf() { return <div> {for fruit in ["Mango", "Guava", "Lychee"] { <button onClick={add(fruit)}>+ {fruit}</button> }} </div> } comp Basket() { return <p class="card"> {cart.length == 0 ? "The basket is empty" : cart.join(", ")} {" "}<button onClick={cart = []}>Empty</button> </p> } document.body.append(<Shelf />, <Basket />)