A buyer puts two books in the cart, then accidentally refreshes the page. The cart is back to 0. To keep the number safe, it needs saving to localStorage every time the cart changes. Work like this happens outside the page itself: saving to localStorage, changing the tab title, writing to the console. It's called a side effect, and in Solid it belongs in an effect, code that runs because a signal changed.
createEffect(fn) runs fn once after the component appears, then again every time a signal read inside fn changes. If you're used to writing useEffect with a dependency list in React, there's no such list here. Think of Nadia's assistant, whose job is to copy the cart number into a notebook every time it changes. Nobody hands him a list of what to watch. He watches exactly the numbers he glanced at the last time he copied. A number he didn't glance at, such as what's in the search box, doesn't make him move.
createEffect: runs after render, then each time its signal changes
Nadia's Bookshop's cart, now with an effect that saves it:
import { createSignal, createEffect } from "solid-js"
function App() {
const [count, setCount] = createSignal(0)
const [search, setSearch] = createSignal("")
console.log("App runs")
createEffect(() => {
localStorage.setItem("cart", count())
console.log("save:", count())
})
return (
<div>
<button onClick={() => setCount(c => c + 1)}>+1 Book</button>
<p>Cart: {count()} books</p>
<input value={search()} onInput={e => setSearch(e.target.value)} placeholder="Search title" />
<p>Searching: {search()}</p>
</div>
)
}
| Event | count() |
Console | localStorage "cart" |
|---|---|---|---|
| Page opens | 0 | App runs, then save: 0 |
"0" |
Click +1 Book |
1 | save: 1 |
"1" |
Type Earth in the search box |
1 | (nothing) | "1" |
| Click again | 2 | save: 2 |
"2" |
createEffect(() => { ... })takes one function. Solid runs it once afterApphas finished and its elements are on the page, sosave: 0prints afterApp runs.- While that function runs, Solid notes which signals are read: here
count(). That's its watch list. There's no dependency array like React'suseEffect. - Every time
setCountchanges the value, the effect runs again.localStoragestores text, so the number2is saved as"2". - Typing in the search box changes
searchand theSearchingtext, but this effect doesn't readsearch(), so it stays still.
The exercise's shape: the tab title
This lesson's exercise uses an effect to write the document title, the text shown on the browser tab:
import { createSignal, createEffect } from "solid-js"
function App() {
const [count, setCount] = createSignal(0)
createEffect(() => {
document.title = `Count: ${count()}`
})
return (
<div>
<p>Count: {count()}</p>
<button onClick={() => setCount(c => c + 1)}>+1</button>
</div>
)
}
document.title = ...changes the tab title. That's a side effect, so it belongs in an effect.`Count: ${count()}`is a template literal:count()is read inside the effect, so the effect follows it. The title isCount: 0when the page appears,Count: 1after one click,Count: 2after two.<p>Count: {count()}</p>reads the same signal, so the paragraph follows too. The+1button adds to the previous value.
Only reads made while the effect runs are tracked
Solid notes reads while the effect function is running, from its first line to its last. A read that happens later isn't noted:
createEffect(() => {
setTimeout(() => {
localStorage.setItem("cart", count())
}, 0)
})
The effect function only sets a timer and finishes. count() is read a moment later, when the effect is no longer running, so Solid notes nothing. The effect runs once, saves "0", and never runs again. Two clicks later the cart is at 2, but localStorage still holds "0".
The same goes for a read after an await in an async effect. So read the signal directly in the effect's body, then hand the value to the code that runs later: const c = count() first, then setTimeout(() => localStorage.setItem("cart", c), 0).
The notes are also rebuilt on every run. An effect if (active()) console.log(count()) running while active() is false doesn't read count(), so at that moment it only watches active.
One setter, one rerun
const [a, setA] = createSignal(1)
createEffect(() => console.log(a()))
setA(2)
setA(3)
The console shows 1, 2, 3. The effect runs once when created (1), then every setter that changes the value runs it again right away (2, then 3). How to make several setters count as one change comes later, in the Advanced Reactivity lesson.
💡 on(): choose what is watched, and defer
import { on } from "solid-js"
createEffect(on(count, (c, previous) => {
localStorage.setItem("cart", c)
console.log("save:", c, "previous:", previous)
}, { defer: true }))
on(count, fn)only watchescount. Signals read insidefnaren't tracked.fnreceives the new value and the previous one.{ defer: true }skips the first run. Nothing is saved when the page opens, and the first click printssave: 1 previous: undefined.
💡 onCleanup: tidy up before the next run
import { onCleanup } from "solid-js"
createEffect(() => {
const c = count()
console.log("save:", c)
onCleanup(() => console.log("cleanup:", c))
})
The function given to onCleanup runs right before the effect runs again, and when the component is thrown away. The first click prints cleanup: 0, then save: 1. This is where you stop a setInterval or remove a listener the effect added.
⚠️ Effects that loop forever, or never run again
- An effect that writes the signal it reads.
createEffect(() => setCount(count() + 1))changescount, which runs the effect again, which changescountagain, on and on until the browser gives up withRangeError: Maximum call stack size exceeded. A value computed from other signals is written as a function or acreateMemo(the next lesson), not as an effect that calls a setter. - Reading a signal in
setTimeoutor afterawait. That read isn't tracked, so the effect stops at its first run. - A React habit.
createEffect(() => { ... }, [count])doesn't throw, but that array is no dependency list:createEffect's second argument is an initial value. What's watched is still what's read inside the function. - Forgetting the parentheses.
`Count: ${count}`writes the function's text into the tab title, and the title never changes. Writecount().
TL;DR: createEffect(() => { ... }) is for side effects: saving to localStorage, changing document.title, logging. The effect runs once after the component appears, then again each time a signal it read changes, with no dependency array. Only reads made while the function is running are tracked: reads in setTimeout or after await don't count. createEffect(() => console.log(a())) then setA(2), setA(3) prints 1, 2, 3. on(signal, fn, { defer: true }) picks what is watched and skips the first run, and onCleanup tidies up before the next run. Don't write a signal the same effect reads: it loops until Maximum call stack size exceeded.
⚡ createEffect for side effects
Write:
const [count, setCount] = createSignal(0)
createEffect(() => {
document.title = `Count: ${count()}`
})
Meaning: Changing the tab title, saving to localStorage or writing to the console are side effects, and they belong in an effect. An effect runs once after the component appears, then again each time a signal it read changes. There's no dependency list like React's useEffect: what's watched is what's read inside it.
⚡ Only reads made while the effect runs are tracked
Write:
createEffect(() => {
setTimeout(() => {
localStorage.setItem("cart", count())
}, 0)
})
Guess first: the +1 button is clicked twice. What does localStorage "cart" hold?
Still "0". count() is read only after the effect function has finished, so Solid notes nothing and the effect never runs again.
Meaning: Read the signal directly in the effect's body, then hand the value to the code that runs later. A read after an await doesn't count either.
⚡ Don't write the signal the same effect reads
Meaning: createEffect(() => setCount(count() + 1)) changes count, which runs the effect again, on and on until the browser gives up with Maximum call stack size exceeded. A value computed from other signals is written as a function or a createMemo.