|
1 | 1 | --- |
2 | | -title: "Derived Reactive Values" |
| 2 | +title: "Effects" |
3 | 3 | order: 4 |
4 | 4 | --- |
5 | 5 |
|
6 | | -[TODO: |
7 | | -Concept page for Effects |
8 | | -- What are Effects |
9 | | -- How to use them |
10 | | -- When to use Effects |
11 | | -- Move relevant sections to ref and vice versa |
12 | | -] |
| 6 | +Effects are reactive functions that run when the values they depend on change. |
| 7 | +They’re the main way to manage side effects that occur outside an application's scope, such as: |
| 8 | +- DOM manipulation |
| 9 | +- Data fetching |
| 10 | +- Subscriptions |
| 11 | + |
| 12 | +## What are Effects? |
| 13 | + |
| 14 | +An effect is a reactive function that **runs automatically whenever the values it depends on change**. |
| 15 | + |
| 16 | +Unlike [signals](/basics/signals) (which store state) or [memos](/basics/derived-state) (which derive state), effects connect your reactive data to the outside world. |
| 17 | +They are used for running code that has side effects, meaning it interacts with or modifies something beyond Solid's reactive graph, such as: |
| 18 | + |
| 19 | +- updating or interacting with the DOM |
| 20 | +- logging values |
| 21 | +- fetching or subscribing to external data |
| 22 | +- setting up or cleaning up resources |
| 23 | + |
| 24 | +Effects run **once when created** to establish its subscriptions, then **again whenever its dependencies change**. |
| 25 | + |
| 26 | +## Creating an Effect |
| 27 | + |
| 28 | +You create an effect using the `createEffect` function. |
| 29 | +It takes a **callback function** as its first argument, which contains the code you want to run reactively. |
| 30 | + |
| 31 | +```tsx |
| 32 | +import { createSignal, createEffect } from "solid-js"; |
| 33 | + |
| 34 | +function Counter() { |
| 35 | + const [count, setCount] = createSignal(0); |
| 36 | + |
| 37 | + createEffect(() => { |
| 38 | + console.log(`Count is: ${count()}`); |
| 39 | + }); |
| 40 | + |
| 41 | + return ( |
| 42 | + <button onClick={() => setCount(count() + 1)}> |
| 43 | + Increment |
| 44 | + </button> |
| 45 | + ); |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +In this example, the effect logs the current value of `count` to the console. |
| 50 | +The effect runs once when created, logging `Count is: 0`, and will run again whenever `count` changes, in this case when the button is clicked. |
| 51 | + |
| 52 | +## Lifecycle of an Effect |
| 53 | + |
| 54 | +An effect goes through a predictable cycle every time it's created and re-runs: |
| 55 | + |
| 56 | +### 1. **Initialization** |
| 57 | + |
| 58 | +When you call `createEffect`, the effect is immediately scheduled to run **once**. |
| 59 | +This first run happens **after the current render phase** finishes, or after the component function returns its JSX. |
| 60 | +This ensures that the DOM is already created and refs are assigned, allowing you to safely interact with the DOM. |
| 61 | + |
| 62 | +```tsx |
| 63 | +createEffect(() => console.log("Initial run")); |
| 64 | +console.log("Hello"); |
| 65 | + |
| 66 | +// Output: |
| 67 | +// Hello |
| 68 | +// Initial run |
| 69 | +``` |
| 70 | + |
| 71 | +### 2. **Dependency tracking** |
| 72 | + |
| 73 | +During its first run, the effect records every reactive value it accesses (such as signals or memos). |
| 74 | +It becomes subscribed to those values, which are now its **dependencies**. |
| 75 | +From then on, the effect automatically re‑runs whenever any of its dependencies change. |
| 76 | + |
| 77 | +```tsx |
| 78 | +const [count, setCount] = createSignal(0); |
| 79 | + |
| 80 | +createEffect(() => { |
| 81 | + console.log(`Count: ${count()}`); |
| 82 | +}); |
| 83 | + |
| 84 | +// Count: 0 runs immediately |
| 85 | +// every setCount(...) re‑runs the effect |
| 86 | +``` |
| 87 | + |
| 88 | +### 3. **Reactive Updates** |
| 89 | + |
| 90 | +Whenever *any* dependency changes, the effects is scheduled to run again. |
| 91 | +This happens **after the current synchronous code completes**, ensuring that all changes are batched together. |
| 92 | +This means that if the dependencies change multiple times in quick succession, the effect will only run *once* after all changes are made: |
| 93 | + |
| 94 | +```tsx |
| 95 | +const [count, setCount] = createSignal(0); |
| 96 | +const [name, setName] = createSignal("Solid"); |
| 97 | + |
| 98 | +createEffect(() => { |
| 99 | + console.log(`Count: ${count()}, Name: ${name()}`); |
| 100 | +}); |
| 101 | + |
| 102 | +setCount(1); |
| 103 | +setName("SolidJS"); |
| 104 | +``` |
| 105 | + |
| 106 | +In this example, the effect will only log `Count: 1, Name: SolidJS` once, after all changes have been made. |
| 107 | + |
| 108 | +### Lifecycle functions |
| 109 | + |
| 110 | +Effects are reactive and run whenever their dependencies change, but sometimes finer control is needed. |
| 111 | +Solid provides lifecycle functions to manage when code runs and how it gets cleaned up. |
| 112 | + |
| 113 | +These functions are especially useful for: |
| 114 | +- Running a side effect **only once** when the component mounts |
| 115 | +- Cleaning up resources, event listeners, or other side effects when the component unmounts |
| 116 | + |
| 117 | +#### `onMount` |
| 118 | + |
| 119 | +The [`onMount`](TODO) function allows you to run code **once** when the component is first added to the DOM. |
| 120 | +Unlike effects, `onMount` does **not track dependencies**. |
| 121 | +It will execute the callback once, and never again. |
| 122 | + |
| 123 | +```tsx |
| 124 | +import { onMount, createSignal, createEffect } from "solid-js"; |
| 125 | + |
| 126 | +function Component() { |
| 127 | + const [data, setData] = createSignal(null); |
| 128 | + |
| 129 | + createEffect(() => { |
| 130 | + // Still runs reactively whenever `data` changes |
| 131 | + console.log("Data:", data()); |
| 132 | + }); |
| 133 | + |
| 134 | + onMount(async () => { |
| 135 | + // Runs only once when the component is mounted |
| 136 | + const res = await fetch("/api/data"); |
| 137 | + setData(await res.json()); |
| 138 | + }); |
| 139 | + |
| 140 | + return <div>...</div>; |
| 141 | +} |
| 142 | +``` |
| 143 | + |
| 144 | +#### `onCleanup` |
| 145 | + |
| 146 | +Use [`onCleanup`](TODO) to **dispose of resources** before a component unmounts, or before an effect re-runs. |
| 147 | +This will prevent memory leaks and ensure that any subscriptions or event listeners are properly removed. |
| 148 | + |
| 149 | +```tsx |
| 150 | +import { createSignal, onCleanup } from "solid-js"; |
| 151 | + |
| 152 | +function App() { |
| 153 | + const [count, setCount] = createSignal(0); |
| 154 | + |
| 155 | + const timer = setInterval(() => setCount(c => c + 1), 1000); |
| 156 | + |
| 157 | + onCleanup(() => { |
| 158 | + // Runs when the component unmounts |
| 159 | + clearInterval(timer); |
| 160 | + }); |
| 161 | + |
| 162 | + return <div>Count: {count()}</div>; |
| 163 | +} |
| 164 | +``` |
| 165 | + |
0 commit comments