Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Signals and Reactivity

Side Effects with createEffect

Learn createEffect in SolidJS: when effects run, how dependencies are tracked, how to clean up, the previous-value argument and mistakes to avoid.

Signals hold state, but state alone does nothing. An effect is a function that reads signals and does something in response: log a message, update the document title, start a timer, call a non-reactive library. createEffect runs your function once and then again whenever one of the signals it read changes.

Your first effect

JavaScript
import { createSignal, createEffect } from "solid-js";

const [name, setName] = createSignal("Ada");

createEffect(() => {
  console.log("Hello,", name());
});
// logs "Hello, Ada" immediately

setName("Grace");
// logs "Hello, Grace"

The effect read name(), so it subscribed to name. There is no list of dependencies to maintain.

An effect that updates the page title and a log

Type in the box and watch the console: the effect runs once at the start and once per change. (The preview is sandboxed, so you will not see the tab title change, but the log proves the effect ran.)

When do effects run?

  • After the DOM exists. The first run happens once the component's elements have been created and attached, so you can safely read refs inside an effect.
  • Synchronously on change. When a signal is written, subscribed effects are scheduled right away, after any surrounding batch finishes (see Batching and untrack).
  • Not on the server. During server-side rendering, effects do not run. Put browser-only work in effects or in onMount.

Cleaning up

An effect can start something that must be stopped before the next run or when the component disappears: a timer, an event listener, a subscription. Call onCleanup inside the effect.

A timer that restarts and cleans up

Press fast and read the console: the old timer is stopped by its cleanup before the effect runs again and starts a new one. Without onCleanup, every change would leave another timer running.

The previous value

An effect function receives the value it returned last time. Return something to keep a running state; pass an initial value as the second argument.

JavaScript
createEffect((prev) => {
  const now = count();
  console.log(`changed from ${prev} to ${now}`);
  return now;           // becomes "prev" next time
}, count());            // initial value for prev
Comparing with the previous run

Effects are for leaving Solid

The purpose of an effect is to talk to something outside the reactive system: the document, the network, a chart library, analytics. Use these better tools for in-Solid work:

You want to... Use
Compute a value from other signals a function or createMemo
Show something that depends on state a JSX expression
Fetch data when a signal changes createResource
Reset one signal when another changes derive it, or write in the event handler

Writing a signal inside an effect in order to keep two values in sync usually signals a design problem. The score demo above does it to show the previous value, but a real app would more often compute the message from the old and new values in the click handler.

  • createRenderEffect: runs during rendering, before the DOM is attached. Solid's own JSX uses it internally. You rarely need it yourself.
  • createComputed: runs immediately and synchronously when its sources change, before render effects. Mostly for library authors.
  • onMount: sugar for an effect that tracks nothing and runs once. See Lifecycle.

Common mistakes

  • Reading a signal after an await. Tracking only works synchronously. Read signals before the first await.
  • Infinite loops. An effect that writes to a signal it also reads re-triggers itself.
  • Forgetting the call. createEffect(() => console.log(count)) logs the function, and never subscribes. Write count().
  • Expecting the order to match the file. Effects run in the order they were created within a component, but depend on the reactive graph, not on line numbers elsewhere.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does createEffect know which signals to watch?

    Reading a signal inside the effect subscribes the effect to it.
  2. 2. Where do you stop a timer started inside an effect?

    onCleanup runs before the next execution and when the effect is disposed.
  3. 3. Do effects run during server-side rendering?

    Server rendering produces HTML only. Effects start after hydration in the browser.
  4. 4. What is passed to an effect function as its argument?

    The second argument of createEffect supplies the initial value of this previous-value parameter.

Summary

  • createEffect(fn) runs fn after rendering and again whenever a signal it read changes.
  • Use onCleanup for timers, listeners and subscriptions.
  • The function receives its previous return value.
  • Effects are for side effects outside Solid; derive values with functions or memos.
  • Read signals synchronously, and do not write to the signals you read.

Next: Derived Values and createMemo