createEffect
createEffect
provides a way to handle side effects in Solid.
Usage
import { createSignal, createEffect } from "solid-js";
function Counter() { const [count, setCount] = createSignal(0);
createEffect(count, (c) => { console.log("Count changed:", c); });
return <button onClick={() => setCount((c) => c + 1)}>{count()}</button>;}
createEffect
accepts two arguments:
- A reactive function to track dependencies of the side effect and return a value.
- A side effect function that will be called with the value returned from the reactive function.
This split protects the side effect from unresolved async signals and ensures that the side effect is only called when all async dependencies are resolved.
import { createAsync, createEffect } from "solid-js";
function UserProfile(props: { userId: string }) { const user = createAsync(() => fetchUser(props.userId));
createEffect(user, (user) => { console.log("User:", user); });
return <div>{user().name}</div>;}
SSR and createEffect
createEffect
never runs on the server:
import { createSignal, createEffect } from "solid-js";
function IsomorphicComponentExample() { const [value] = createSignal(0);
createEffect(value, (value) => { // This code never runs on server alert(`Signal value: ${value}`); });
return <p>Signal value: {value()}</p>;}
Making onMount
(runs on the client)
Solid ^2.0
doesn't provide onMount
function from Solid ^1.0
, but you can easily simulate it:
import { createEffect } from "solid-js";
const onMount = (fn: VoidFunction) => createEffect(() => void 0, fn);
function OnMountExample() { onMount(() => { console.log("Log from `onMount`"); });
return <p>Test component</p>;}
Last updated: 5/3/25, 4:28 AM
Edit this page on GitHub