In the Store Mutations lesson, two setShop calls in one click made the effect run twice and catch a half-finished state. It's like a till at Nadia's Bookshop that prints a receipt after every item scanned: a buyer of two books gets a half-finished receipt midway. A proper cashier scans everything first, then prints one receipt.
Solid notes who reads which signal, then reruns only what it needs to. This lesson gives you tools to steer those notes: batch merges several changes into one round, untrack and on choose what is tracked, createRoot makes an owner you take down yourself, and createSelector and createDeferred keep a big list light.
batch: one round for many changes
The exercise's shape, plus one logging effect:
import { createSignal, createEffect, batch } from "solid-js"
function App() {
const [count, setCount] = createSignal(0)
const [name, setName] = createSignal("Andi")
createEffect(() => console.log(name() + ": " + count()))
const updateAll = () => {
batch(() => {
setCount((c) => c + 1)
setName("Budi")
})
}
return (
<div>
<p>{name()}: {count()}</p>
<button onClick={updateAll}>Update</button>
</div>
)
}
Tested in Solid 1.9, one click from Andi: 0:
updateAll |
Console | Effect runs |
|---|---|---|
without batch |
Andi: 1, then Budi: 1 |
2 times |
with batch |
Budi: 1 |
1 time |
Without batch, it prints Andi: 1 then Budi: 1. Each setter runs its readers right away, so the effect gets to see Andi: 1, a half-finished state nobody meant.
batch(() => { ... })runs its function, and the affected effects run only once, after the function finishes. So with two setters insidebatch, an effect reading both runs 1 time.- The signals themselves change right away. Reading
count()insidebatchaftersetCount(5)gives5. Only the effects wait. setCount((c) => c + 1)reads the old value, so a second click givesBudi: 2. The exercise checks the<p>saysAndi: 0, thenBudi: 1, thenBudi: 2.
untrack: reading without subscribing
createEffect(() => console.log(untrack(name) + ": " + count()))
Tested: setName("Budi") doesn't run the effect. setCount(1) afterwards prints Budi: 1. untrack(fn) calls fn without noting the read, so the effect only reruns because of count, yet still reads the latest name when it runs. A signal is a function, so untrack(name) is enough, the same as untrack(() => name()).
on: naming the source yourself
createEffect(on(count, (value, previous) => {
console.log(previous, "->", value, "· name:", name())
}))
on(count, fn)tracks onlycount. Other reads insidefn, such asname(), aren't tracked.fngets the new value and the previous one. Tested: the first run printsundefined -> 0 · name: Andi,setName("Budi")prints nothing,setCount(1)prints0 -> 1 · name: Budi.on(count, fn, { defer: true })skips the first run, sofnonly runs whencountreally changes.
createRoot and owners
Every effect and memo has an owner: the component or root it was made in. When its owner is taken down, the effect stops and its onCleanup runs. Solid takes components down. createRoot makes an owner you take down yourself:
const [count, setCount] = createSignal(0)
const dispose = createRoot((dispose) => {
createEffect(() => console.log("effect:", count())) // effect: 0
onCleanup(() => console.log("cleaned up"))
return dispose
})
setCount(1) // effect: 1
dispose() // cleaned up
setCount(2) // prints nothing
- An effect made outside any owner, inside a
setTimeoutor after anawaitfor example, will never be taken down. Solid's development mode warns about it:computations created outside a `createRoot` or `render` will never be disposed. getOwner()takes the current owner, andrunWithOwner(owner, fn)runsfnunder that owner. Tested: inside asetTimeout,getOwner()isnull, and anonCleanupset throughrunWithOwnerstill runs when its root is taken down.
Big lists: createSelector and createDeferred
A shelf of 1,000 books, with the selected one marked:
const [selected, setSelected] = createSignal(1)
const isSelected = createSelector(selected)
<For each={shelf}>
{(b) => <li classList={{ picked: isSelected(b.id) }}>{b.title}</li>}
</For>
| Each row reads | Pick another book: rows recomputed |
|---|---|
selected() === b.id |
1,000 rows |
isSelected(b.id) |
2 rows (the old one and the new one) |
Tested in Solid 1.9 with 1,000 effects. createSelector(source) notes its readers per key, so a change only wakes the rows whose result changes.
createDeferred(search, { timeoutMs: 500 }) gives a copy of search that follows later, when the browser has time to spare, 500 ms at the latest. Tested: right after search was changed three times to rain, the copy still held "", then it changed once to rain. A heavy shelf filter reads the copy, so the search box stays smooth to type in.
⚠️ Effects that run too often, or never stop
- Forgetting
batchwhen changing several signals read together. The effect runs several times and gets to see a half-finished state, likeAndi: 1. untrack(name())with parentheses.name()is already read (and tracked) beforeuntrackruns, thenuntracktries to call"Andi":TypeError: fn is not a function. Writeuntrack(name).- An effect inside
setTimeoutor afterawait. It has no owner, so it never stops. UserunWithOwner, or make the effect in the component body. - Exercise:
setCount(1)instead ofsetCount((c) => c + 1). The second click must giveBudi: 2. Your code must also containbatchand a<button>.
TL;DR: batch(() => { setCount((c) => c + 1); setName("Budi") }) runs the affected effects once, after every change; without batch, the effect runs twice and gets to see Andi: 1. untrack(name) reads without tracking, and on(count, (value, previous) => ...) only tracks the named source (defer: true skips the first run). Every effect has an owner; createRoot((dispose) => ...) makes an owner taken down with dispose(), and an effect inside setTimeout needs runWithOwner. For a big list, createSelector makes a new selection recompute only 2 rows, not 1,000, and createDeferred delays a value for heavy work.
⚡ batch: one round for many changes
Write:
const updateAll = () => {
batch(() => {
setCount((c) => c + 1)
setName("Budi")
})
}
Guess first: there's an effect console.log(name() + ": " + count()), and updateAll is written without batch. What does one click from Andi: 0 print?
Andi: 1, then Budi: 1. Each setter runs its readers right away, so the effect gets to see a half-finished state. With batch, only Budi: 1.
Meaning: The signals still change right away; only the effects wait until the batch function finishes.
⚡ untrack and on: choose what is tracked
Write:
createEffect(() => console.log(untrack(name) + ": " + count()))
Meaning: untrack(name) reads without noting the read, so this effect only reruns because of count. Write it without parentheses: untrack(name()) is already read before untrack runs. on(count, fn) also tracks only count.
⚡ Every effect has an owner
Meaning: An owner is the component or root an effect was made in. When its owner is taken down, the effect stops. createRoot((dispose) => ...) makes an owner you take down yourself with dispose(). An effect inside a setTimeout has no owner, so it never stops.