mirror of
https://github.com/Dvorinka/Devour.git
synced 2026-06-04 12:33:04 +00:00
17 lines
8.7 KiB
JSON
17 lines
8.7 KiB
JSON
{
|
|
"id": "53fd34aef011e76f81924f5d",
|
|
"source": "solid:signals",
|
|
"type": "github-document",
|
|
"title": "effects",
|
|
"content": "---\ntitle: Effects\norder: 4\nuse_cases: \u003e-\n side effects, dom manipulation, api calls, subscriptions, logging, reacting to\n state changes\ntags:\n - effects\n - side-effects\n - reactivity\n - lifecycle\n - subscriptions\nversion: '1.0'\ndescription: \u003e-\n Manage side effects like DOM updates, API calls, and subscriptions that\n respond automatically to reactive state changes.\n---\n\nEffects are functions that are triggered when the signals they depend on change.\nThey play a crucial role in managing side effects, which are actions that occur outside of the application's scope, such as DOM manipulations, data fetching, and subscriptions.\n\n## Using an effect\n\nAn effect is created using the `createEffect` function.\nThis function takes a callback as its argument that runs when the effect is triggered.\n\n```jsx\nimport { createEffect } from \"solid-js\";\n\nconst [count, setCount] = createSignal(0);\n\ncreateEffect(() =\u003e {\n\tconsole.log(count());\n});\n```\n\nIn this example, an effect is created that logs the current value of `count` to the console.\nWhen the value of `count` changes, the effect is triggered, causing it to run again and log the new value of `count`.\n\n:::note\nEffects are primarily intended for handling side effects that do not write to the reactive system.\nIt's best to avoid setting signals within effects, as this can lead to additional rendering or even infinite loops if not managed carefully.\nInstead, it is recommended to use [createMemo](/reference/basic-reactivity/create-memo) to compute new values that rely on other reactive values.\n:::\n\n## Managing dependencies\n\nEffects can be set to observe any number of dependencies.\nDependencies are what allow an effect to track changes and respond accordingly.\nThese can include signals, props, context, or any other reactive values.\nWhen any of these change, the effect is notified and will run again to update its state.\n\nUpon initialization, an effect will run _once_, regardless of whether it has any dependencies.\nThis is useful for setting up the effect and initializing variables or subscribing to [signals](/concepts/signals).\nAfter this run, the effect will only be triggered when any of its _dependencies_ change.\n\n```jsx\ncreateEffect(() =\u003e {\n\tconsole.log(\"hello\"); // will run only once\n});\n\ncreateEffect(() =\u003e {\n\tconsole.log(count()); // will run every time count changes\n});\n```\n\nSolid automatically tracks the dependencies of an effect, so you do not need to manually specify them.\nThis improves the tracking and minimizes the chances of overlooking or incorrectly identifying dependencies.\n\n## Subscribing to signals\n\nWhen an effect is set to observe a signal, it creates a subscription to it.\nThis subscription allows the effect to track the changes in the signal's value, which causes it to observe any changes that may happen and to execute its callback accordingly.\n\n```jsx\nimport { createSignal, createEffect } from \"solid-js\";\n\nconst [count, setCount] = createSignal(0);\n\ncreateEffect(() =\u003e {\n\tconsole.log(count()); // Logs current value of count whenever it changes\n});\n```\n\n### Managing multiple signals\n\nEffects have the ability to observe multiple signals.\nA single effect can subscribe to multiple signals, and similarly, multiple effects can keep track of a single signal.\nThis is useful when you need to update the UI based on multiple signals.\n\nWhen multiple signals are observed within a single effect, it will execute its callback whenever _any_ of the signals change.\nThe effect will run even if only one of the signals changes, not necessarily all of them.\nThis means that the effect will run with the latest values of all of the signals that it is observing.\n\n```jsx\nimport { createSignal, createEffect } from \"solid-js\";\n\nconst [count, setCount] = createSignal(0);\nconst [message, setMessage] = createSignal(\"Hello\");\n\ncreateEffect(() =\u003e {\n\tconsole.log(count(), message());\n});\n\nsetCount(1); // Output: 1, \"Hello\"\nsetMessage(\"World\"); // Output: 1, \"World\"\n```\n\n:::note\nWhen a signal updates, it notifies all of its subscribers sequentially but the *order can vary*.\nWhile effects are guaranteed to run when a signal updates, the execution might **not** be instantaneous.\nThis means that the order of execution of effects is *not guaranteed* and should not be relied upon.\n:::\n\n### Nested effects\n\nWhen working with effects, it is possible to nest them within each other.\nThis allows each effect to independently track its own dependencies, without affecting the effect that it is nested within.\n\n```jsx\ncreateEffect(() =\u003e {\n\tconsole.log(\"Outer effect starts\");\n\tcreateEffect(() =\u003e console.log(\"Inner effect\"));\n\tconsole.log(\"Outer effect ends\");\n});\n```\n\nThe order of execution is important to note.\nAn inner effect will _not_ affect the outer effect.\nSignals that are accessed within an inner effect, will _not_ be registered as dependencies for the outer effect.\nWhen the signal located within the inner effect changes, it will trigger only the _inner effect_ to re-run, not the outer one.\n\n```jsx\nimport { createSignal, createEffect } from \"solid-js\";\n\nconst [count, setCount] = createSignal(0);\n\ncreateEffect(() =\u003e {\n\tconsole.log(\"Outer effect starts\");\n\tcreateEffect(() =\u003e console.log(count())); // when count changes, only this effect will run\n\tconsole.log(\"Outer effect ends\");\n});\n```\n\nThis forces each effect to be independent of each other, which helps to avoid unexpected behaviour.\nAdditionally, it allows you to create effects that are only triggered when certain conditions are met.\n\n## Lifecycle functions\n\nEffects have a lifecycle that can be managed using certain functions.\nThese functions allow you to control the initialization and disposal of effects to build the type of behaviour that you need.\nThis can include running a side effect only once, or cleaning up a task when it is no longer needed.\n\n### `onMount`\n\nIn situations where you just want to run a side effect **once**, you can use the [`onMount`](/reference/lifecycle/on-mount) function.\nThis lifecycle function is similar to an effect, but it does not track any dependencies.\nRather, once the component has been initialized, the `onMount` callback will be executed and will not run again.\n\n```jsx\nimport { onMount } from \"solid-js\";\n\nfunction Component() {\n\tconst [data, setData] = createSignal(null);\n\n\tcreateEffect(() =\u003e {\n\t\tdata(); // will run every time data changes\n\t});\n\n\tonMount(async () =\u003e {\n\t\t// will run only once, when the component is mounted\n\t\tconst fetchedData = await fetch(\"https://example.com/data\");\n\t\tsetData(fetchedData);\n\t});\n\n\treturn \u003cdiv\u003e...\u003c/div\u003e;\n}\n```\n\n`onMount` provides the assurance that the callback will only run once.\nIf using an effect in this situation, there is no guarantee that it will only run once, which can lead to unexpected behaviour.\nThis makes `onMount` useful for API calls and other side effects that only need to be run once per component instance.\n\n### `onCleanup`\n\nWhile `onMount` is useful for running a side effect once, [`onCleanup`](/reference/lifecycle/on-cleanup) is helpful for cleaning up a task when it is no longer needed.\n`onCleanup` will run whenever the component unmounts, removing any subscriptions that the effect has.\n\n```jsx\nimport { onCleanup } from \"solid-js\";\n\nfunction App() {\n\tconst [count, setCount] = createSignal(0);\n\n\tconst timer = setInterval(() =\u003e {\n\t\tsetCount((prev) =\u003e prev + 1);\n\t}, 1000);\n\n\tonCleanup(() =\u003e {\n\t\tclearInterval(timer);\n\t});\n\n\treturn \u003cdiv\u003eCount: {count()}\u003c/div\u003e;\n}\n```\n\nIn this example, the `onCleanup` function is used to clear the interval that is set up in the effect.\nTo avoid the interval from running indefinitely, the `onCleanup` function is used to clear the interval once the component unmounts.\n\n`onCleanup` can be used to avoid memory leaks.\nThese occur when a component is unmounted, but references to it still exist and, as a result, could still be running in the background.\nUsing `onCleanup` to remove any subscriptions or references to the component can help to avoid this issue.",
|
|
"url": "https://github.com/solidjs/solid-docs/blob/HEAD/src/routes/concepts/effects.mdx",
|
|
"metadata": {
|
|
"path": "src/routes/concepts/effects.mdx",
|
|
"repo": "solidjs/solid-docs",
|
|
"repo_url": "https://github.com/solidjs/solid-docs.git",
|
|
"size": 7975,
|
|
"source_type": "github"
|
|
},
|
|
"hash": "945483995bcd45a2bfc8724ab9d2478b98b35a26ba1d6434ca9335ef430ca36a",
|
|
"timestamp": "2026-02-23T11:43:00.186762949+01:00"
|
|
} |