Skip to content
6 changes: 6 additions & 0 deletions src/routes/concepts/effects.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ createEffect(() => {
In this example, an effect is created that logs the current value of `count` to the console.
When the value of `count` changes, the effect is triggered, causing it to run again and log the new value of `count`.

:::note
Effects are primarily intended for handling side effects that do not write to the reactive system.
It's best to avoid setting signals within effects, as this can lead to additional rendering or even infinite loops if not managed carefully.
Instead, it is recommended to use [createMemo](/reference/basic-reactivity/create-memo) to compute new values that rely on other reactive values.
:::

## Managing dependencies

Effects can be set to observe any number of dependencies.
Expand Down
201 changes: 123 additions & 78 deletions src/routes/reference/basic-reactivity/create-effect.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,109 +10,154 @@ tags:
- reactivity
- lifecycle
- cleanup
version: '1.0'
version: "1.0"
description: >-
Learn how to use createEffect to run side effects when reactive dependencies
change. Perfect for DOM manipulation and external library integration.
---

```tsx
import { createEffect } from "solid-js"
The `createEffect` primitive creates a reactive computation.
It automatically tracks reactive values, such as signals, that are accessed within the provided function.
This function re-runs whenever any of its dependencies change.

## Execution Timing

- The initial run of an effect is scheduled to run **after the current rendering phase completes**.
- This means it runs after all synchronous code in a component has been executed and the DOM elements have been created, but **before the browser paints them to the screen**.
- As a result, [refs](/concepts/refs) **are set** before the effect runs for the first time, even though the DOM nodes may **not be attached to the main document tree**.
This is particularly relevant when using [`children`](/reference/component-apis/children).
- If multiple dependencies are updated within the same batch, the effect only runs once.
- Effects always run **after** any pure computations (like [memos](/concepts/derived-values/memos)) in the same update cycle.
- The order in which effects run is **not guaranteed**.
- Effects are **not run** during Server-Side Rendering (SSR) or the initial client hydration.

function createEffect<T>(fn: (v: T) => T, value?: T): void
## Import

```ts
import { createEffect } from "solid-js";
```

Effects are a general way to make arbitrary code ("side effects") run whenever dependencies change, e.g., to modify the DOM manually.
`createEffect` creates a new computation that runs the given function in a tracking scope, thus automatically tracking its dependencies, and automatically reruns the function whenever the dependencies update.
## Type

```ts
function createEffect<Next>(
fn: EffectFunction<undefined | NoInfer<Next>, Next>
): void;
function createEffect<Next, Init = Next>(
fn: EffectFunction<Init | Next, Next>,
value: Init,
options?: { name?: string }
): void;
function createEffect<Next, Init>(
fn: EffectFunction<Init | Next, Next>,
value?: Init,
options?: { name?: string }
): void;
```

For example:
## Parameters

```tsx
const [a, setA] = createSignal(initialValue)
### `fn`

// effect that depends on signal `a`
createEffect(() => doSideEffect(a()))
```
- **Type:** `EffectFunction<undefined | NoInfer<Next> | EffectFunction<Init | Next, Next>`
- **Required:** Yes

The effect will run whenever `a` changes value.
The function to run.
It receives the value returned from the previous run, or the initial `value` on the first run.
The value it returns is passed to the next run.

The effect will also run once, immediately after it is created, to initialize the DOM to the correct state. This is called the "mounting" phase.
However, we recommend using `onMount` instead, which is a more explicit way to express this.
### `value`

The effect callback can return a value, which will be passed as the `prev` argument to the next invocation of the effect.
This is useful for memoizing values that are expensive to compute. For example:
- **Type:** `Init`
- **Required:** No

```tsx
const [a, setA] = createSignal(initialValue)

// effect that depends on signal `a`
createEffect((prevSum) => {
// do something with `a` and `prevSum`
const sum = a() + prevSum
if (sum !== prevSum) console.log("sum changed to", sum)
return sum
}, 0)
// ^ the initial value of the effect is 0
```
The initial value passed to `fn` on its first run.

Effects are meant primarily for side effects that read but don't write to the reactive system: it's best to avoid setting signals in effects, which without care can cause additional rendering or even infinite effect loops. Instead, prefer using [createMemo](/reference/basic-reactivity/create-memo) to compute new values that depend on other reactive values, so the reactive system knows what depends on what, and can optimize accordingly.
If you do end up setting a signal within an effect, computations subscribed to that signal will be executed only once the effect completes; see [`batch`](/reference/reactive-utilities/batch) for more detail.
### `options`

The first execution of the effect function is not immediate; it's scheduled to run after the current rendering phase (e.g., after calling the function passed to [render](/reference/rendering/render), [createRoot](/reference/reactive-utilities/create-root), or [runWithOwner](/reference/reactive-utilities/run-with-owner)).
If you want to wait for the first execution to occur, use [queueMicrotask](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) (which runs before the browser renders the DOM) or `await Promise.resolve()` or `setTimeout(..., 0)` (which runs after browser rendering).
- **Type:** `{ name?: string }`
- **Required:** No

```tsx
// assume this code is in a component function, so is part of a rendering phase
const [count, setCount] = createSignal(0)

// this effect prints count at the beginning and when it changes
createEffect(() => console.log("count =", count()))
// effect won't run yet
console.log("hello")
setCount(1) // effect still won't run yet
setCount(2) // effect still won't run yet

queueMicrotask(() => {
// now `count = 2` will print
console.log("microtask")
setCount(3) // immediately prints `count = 3`
console.log("goodbye")
})

// --- overall output: ---
// hello
// count = 2
// microtask
// count = 3
// goodbye
```
An optional configuration object with the following properties:

#### `name`

- **Type:** `string`
- **Required:** No

A name for the effect, used for identification in debugging tools like [Solid Debugger](https://github.com/thetarnav/solid-devtools).

This delay in first execution is useful because it means an effect defined in a component scope runs after the JSX returned by the component gets added to the DOM.
In particular, [refs](/reference/jsx-attributes/ref) will already be set.
Thus you can use an effect to manipulate the DOM manually, call vanilla JS libraries, or other side effects.
## Return value

Note that the first run of the effect still runs before the browser renders the DOM to the screen (similar to React's `useLayoutEffect`).
If you need to wait until after rendering (e.g., to measure the rendering), you can use `await Promise.resolve()` (or `Promise.resolve().then(...)`), but note that subsequent use of reactive state (such as signals) will not trigger the effect to rerun, as tracking is not possible after an async function uses `await`.
Thus you should use all dependencies before the promise.
`createEffect` does not return a value.

If you'd rather an effect run immediately even for its first run, use [createRenderEffect](/reference/secondary-primitives/create-render-effect) or [createComputed](/reference/secondary-primitives/create-computed).
## Examples

### Basic Usage

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

function Counter() {
const [count, setCount] = createSignal(0);

// Every time count changes this effect re-runs.
createEffect(() => {
console.log("Count incremented! New value: ", count());
});

return (
<div>
<p>Count: {count()}</p>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
</div>
);
}
```

You can clean up your side effects in between executions of the effect function by calling [onCleanup](/reference/lifecycle/on-cleanup) inside the effect function.
Such a cleanup function gets called both in between effect executions and when the effect gets disposed (e.g., the containing component unmounts).
For example:
### Execution Timing

```tsx
// listen to event dynamically given by eventName signal
createEffect(() => {
const event = eventName()
const callback = (e) => console.log(e)
ref.addEventListener(event, callback)
onCleanup(() => ref.removeEventListener(event, callback))
})
import { createSignal, createEffect, createRenderEffect } from "solid-js";

function Counter() {
const [count, setCount] = createSignal(0);

// This is part of the component's synchronous execution.
console.log("Hello from counter");

// This effect is scheduled to run after the initial render is complete.
createEffect(() => {
console.log("Effect:", count());
});

// By contrast, a render effect runs synchronously during the render phase.
createRenderEffect(() => {
console.log("Render effect:", count());
});

// Setting a signal during the render phase re-runs render effects, but not effects, which are
// still scheduled.
setCount(1);

// A microtask is scheduled to run after the current synchronous code (the render phase) finishes.
queueMicrotask(() => {
// Now that rendering is complete, signal updates will trigger effects immediately.
setCount(2);
});
}

// Output:
// Hello from counter
// Render effect: 0
// Render effect: 1
// Effect: 1
// Render effect: 2
// Effect: 2
```

## Arguments
## Related

- `fn` - The function to run in a tracking scope. It can return a value, which will be passed as the `prev` argument to the next invocation of the effect.
- `value` - The initial value of the effect. This is useful for memoizing values that are expensive to compute.
- [`createRenderEffect`](/reference/secondary-primitives/create-render-effect)
- [`onCleanup`](/reference/lifecycle/on-cleanup)
- [`onMount`](/reference/lifecycle/on-mount)
Loading