diff --git a/src/routes/concepts/effects.mdx b/src/routes/concepts/effects.mdx index fbe55d14e..adb73f395 100644 --- a/src/routes/concepts/effects.mdx +++ b/src/routes/concepts/effects.mdx @@ -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. diff --git a/src/routes/reference/basic-reactivity/create-effect.mdx b/src/routes/reference/basic-reactivity/create-effect.mdx index 760632341..84ee13f12 100644 --- a/src/routes/reference/basic-reactivity/create-effect.mdx +++ b/src/routes/reference/basic-reactivity/create-effect.mdx @@ -10,109 +10,165 @@ 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](/concepts/signals), accessed within the provided function. +This function will re-run whenever any of its dependencies change. -function createEffect(fn: (v: T) => T, value?: T): void +## Execution Timing -``` +### Initial Run -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. +- The initial run of effects is **scheduled to occur after the current rendering phase completes**. +- It runs after all synchronous code in a component has finished and DOM elements have been created, but **before the browser paints them on the screen**. +- **[Refs](/concepts/refs) are set** before the first run, even though DOM nodes may not yet be attached to the main document tree. + This is relevant when using the [`children`](/reference/component-apis/children) helper. -For example: +### Subsequent Runs -```tsx -const [a, setA] = createSignal(initialValue) +- After the initial run, the effect **re-runs whenever any tracked dependency changes**. +- When multiple dependencies change within the same batch, the effect **runs once per batch**. +- The **order of runs** among multiple effects is **not guaranteed**. +- Effects always run **after** all pure computations (such as [memos](/concepts/derived-values/memos)) within the same update cycle. -// effect that depends on signal `a` -createEffect(() => doSideEffect(a())) -``` +### Server-Side Rendering -The effect will run whenever `a` changes value. +- Effects **never run during SSR**. +- Effects also **do not run during the initial client hydration**. -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. +## Import -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: +```ts +import { createEffect } from "solid-js"; +``` -```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 +## Type + +```ts +function createEffect( + fn: EffectFunction, Next> +): void; +function createEffect( + fn: EffectFunction, + value: Init, + options?: { name?: string } +): void; +function createEffect( + fn: EffectFunction, + value?: Init, + options?: { name?: string } +): void; ``` -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. +## Parameters -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). +### `fn` -```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 -``` +- **Type:** `EffectFunction | EffectFunction` +- **Required:** Yes + +A function to be executed as the effect. + +It receives the value returned from the previous run, or the initial `value` during the first run. +The value returned by `fn` is passed to the next run. + +### `value` + +- **Type:** `Init` +- **Required:** No -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. +The initial value passed to `fn` during its first run. -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. +### `options` -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). +- **Type:** `{ name?: string }` +- **Required:** No + +An optional configuration object with the following properties: + +#### `name` + +- **Type:** `string` +- **Required:** No + +A name for the effect, which can be useful for identification in debugging tools like the [Solid Debugger](https://github.com/thetarnav/solid-devtools). + +## Return value + +`createEffect` does not return a value. + +## 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 ( +
+

Count: {count()}

+ +
+ ); +} +``` -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) diff --git a/src/routes/reference/secondary-primitives/create-render-effect.mdx b/src/routes/reference/secondary-primitives/create-render-effect.mdx index 0c5083f14..03ba5016b 100644 --- a/src/routes/reference/secondary-primitives/create-render-effect.mdx +++ b/src/routes/reference/secondary-primitives/create-render-effect.mdx @@ -10,62 +10,164 @@ tags: - immediate - refs - lifecycle -version: '1.0' +version: "1.0" description: >- Execute effects immediately during rendering with createRenderEffect. Run side effects as DOM creates, before refs are set or connected. --- +The `createRenderEffect` primitive creates a reactive computation that automatically tracks reactive values, such as [signals](/concepts/signals), accessed within the provided function. +This function re-runs whenever any of its dependencies change. + +## Execution Timing + +### Initial Run + +- A render effect runs **synchronously during the current rendering phase**, while DOM elements are being created or updated. +- It **runs before elements are mounted** to the DOM. +- **[Refs](/concepts/refs) are not set** during this initial run. + +### Subsequent Runs + +- After the initial render, the render effect **re-runs whenever any of its tracked dependencies change**. +- Re-runs occur **after** all pure computations (such as [memos](/concepts/derived-values/memos)) have completed within the same update cycle. +- When multiple dependencies change within the same batch, the render effect **runs once per batch**. +- The **order of re-runs** among multiple render effects is **not guaranteed**. + +### Server-Side Rendering + +- During SSR, render effects **run once on the server**, since they are part of the synchronous rendering phase. +- On the client, an initial run still occurs during the client rendering phase to initialize the reactive system; + that client initial run is separate from the server run. +- After hydration, subsequent runs occur on the client when dependencies change. + +## Import + ```ts -import { createRenderEffect } from "solid-js" +import { createRenderEffect } from "solid-js"; +``` -function createRenderEffect(fn: (v: T) => T, value?: T): void +## Type +```ts +function createRenderEffect( + fn: EffectFunction, Next> +): void; +function createRenderEffect( + fn: EffectFunction, + value: Init, + options?: { name?: string } +): void; +function createRenderEffect( + fn: EffectFunction, + value?: Init, + options?: { name?: string } +): void; ``` -A render effect is a computation similar to a regular effect (as created by [`createEffect`](/reference/basic-reactivity/create-effect)), but differs in when Solid schedules the first execution of the effect function. -While `createEffect` waits for the current rendering phase to be complete, `createRenderEffect` immediately calls the function. -Thus the effect runs as DOM elements are being created and updated, but possibly before specific elements of interest have been created, and probably before those elements have been connected to the document. -In particular, **refs** will not be set before the initial effect call. -Indeed, Solid uses `createRenderEffect` to implement the rendering phase itself, including setting of **refs**. +## Parameters -Reactive updates to render effects are identical to effects: they queue up in response to a reactive change (e.g., a single signal update, or a batch of changes, or collective changes during an entire render phase) and run in a single [`batch`](/reference/reactive-utilities/batch) afterward (together with effects). -In particular, all signal updates within a render effect are batched. +### `fn` -Here is an example of the behavior. (Compare with the example in [`createEffect`](/reference/basic-reactivity/create-effect).) +- **Type:** `EffectFunction | EffectFunction` +- **Required:** Yes -```ts -// 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 -createRenderEffect(() => console.log("count =", count())) -// render effect runs immediately, printing `count = 0` -console.log("hello") -setCount(1) // effect won't run yet -setCount(2) // effect won't run yet - -queueMicrotask(() => { - // now `count = 2` will print - console.log("microtask") - setCount(3) // immediately prints `count = 3` - console.log("goodbye") -}) - -// --- overall output: --- -// count = 0 [this is the only added line compared to createEffect] -// hello -// count = 2 -// microtask -// count = 3 -// goodbye +A function to be executed as the render effect. + +It receives the value returned from the previous run, or the initial `value` during the first run. +The value returned by `fn` is passed to the next run. + +### `value` + +- **Type:** `Init` +- **Required:** No + +The initial value passed to `fn` during its first run. + +### `options` + +- **Type:** `{ name?: string }` +- **Required:** No + +An optional configuration object with the following properties: + +#### `name` + +- **Type:** `string` +- **Required:** No + +A name for the render effect, which can be useful for identification in debugging tools like the [Solid Debugger](https://github.com/thetarnav/solid-devtools). + +## Return value + +`createRenderEffect` does not return a value. + +## Examples + +### Basic Usage + +```tsx +import { createSignal, createRenderEffect } from "solid-js"; + +function Counter() { + const [count, setCount] = createSignal(0); + + // This runs immediately during render, and re-runs when the count changes. + createRenderEffect(() => { + console.log("Count: ", count()); + }); + + return ( +
+

Count: {count()}

+ +
+ ); +} ``` -Just like `createEffect`, the effect function gets called with an argument equal to the value returned from the effect function's last execution, or on the first call, equal to the optional second argument of `createRenderEffect`. +### Execution Timing + +```tsx +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 -| Name | Type | Description | -| :------ | :------------ | :----------------------------------------------------- | -| `fn` | `(v: T) => T` | The effect function to be called. | -| `value` | `T` | The initial value to be passed to the effect function. | +- [`createEffect`](/reference/basic-reactivity/create-effect) +- [`onCleanup`](/reference/lifecycle/on-cleanup)