DEV Community

Cover image for The zen of state in Solid.js

The zen of state in Solid.js

Alex Lohr on January 24, 2024

Cover image from https://www.pxfuel.com/en/free-photo-jsrnn Solid.js is a frontend framework that is known for its superficial similarities and ot...
Collapse
 
peerreynders profile image
peerreynders

One of its best parts is its signals-based state management.

I'd say it goes deeper than that. “Solid is a state library that happens to render”:

Components Are Pure Overhead - YouTube

With many starting to look at incorporating Reactivity into existing Frameworks I wanted to take a moment to look at how Frameworks evolved into using Compon...

favicon youtube.com

With React rendering is front and center; state management is only a secondary concern in as far as it is necessary to determine when to re-render.

5th Koan: Use memos as a reactivity filter when you face performance issues; avoid premature optimization.

But the default should be derived signals; createMemo() should be the exception.

While not an API, derived signals are a primitive concept so I'm a bit surprised to not see them in the new docs.

In Solid.js, resources are a way to handle asynchronous state.

One pain point is combining resources with stores (as resources are strictly signals). SolidJS 1.5 introduced the experimental storage option to deal with that - (though it's not exactly intuitive how it works).

However createAsync() doesn't support a storage option yet (probably by SolidJS 2.0). It wasn't until I found this that I figured out what is going on.

// Combining async with Store.
// Note: briefs is a signal carrying a finer grained store
const initialValue: NoteBrief[] = [];
const [briefsStore, setBriefs] = createStore(initialValue);
const briefs = createAsync(
  async () => {
    const next = await getBriefs(searchParams.search);
    setBriefs(reconcile(next));
    return briefsStore;
  },
  { initialValue }
);
Enter fullscreen mode Exit fullscreen mode

Essentially the store is reconciled inside the fetcher and the resource value is the fine-grained store itself.

The other thing I still have yet to discover: How do you use reactivity temporarily? How do you terminate unwanted subscriptions created by createEffect() and createMemo()? Perhaps I have to create a new root before I have to wire up anything temporary?

Good luck in finding your next opportunity and may it be better than all the ones before it!

Collapse
 
amustafa16421 profile image
Mustafa_A

Well, I also admire your persistence.
You must have been through something to be able to produce this guide :-)
Congrats.

I never used solid.js ( I am currently with Elm ), however I can tell that this a well-thought-out and well structured guide. 👍