Hands-on with Solid: Reactive programming with signals

Signals and effects

Because Solid components are a function call, they only execute once upon creation. Therefore, if you had a signal that you needed to access outside of the template, you would have to wrap it in an effect. Inside the JSX, you can just call the signal getter, like we have just done with count(), and it will give you the reactive value as it changes. However, in the body of the function, you need to use an effect:

console.log("Count:",count()); // ❌ not tracked - only runs once during initialization.

createEffect(()=>{  console.log(count()); // ✅ will update whenever `count()` changes.
});
// snippet from the docs

So, useEffect is a kind of ad hoc observer for signals. Anytime you need to perform some out-of-template effect based on a signal, that is what you need to use. Between createSignal, createEffect, and the native reactivity of JSX, you have most of the basic elements of reactivity.

Fetching a remote API with createResource

Solid layers capabilities on top of the basic features of signals. One of those capabilities is createResource, which makes it easy to handle asynchronous requests in a reactive way. This is a simple layer on top of createSignal. Let’s use it create a Joke component that fetches 10 jokes from the Joke API and displays them.

Donner Music, make your music with gear
Multi-Function Air Blower: Blowing, suction, extraction, and even inflation

Leave a reply

Please enter your comment!
Please enter your name here