DEV Community

Kirill Novgorodtsev
Kirill Novgorodtsev

Posted on

Still Playing Catch-Up: A Look at Solid 2

Solid 2 brings a new reactivity system. In the announcement, Ryan Carniato writes:

Today signals are everywhere.

Well, let's see how it turned out.

Benchmarks

We'll use this benchmark to test how well each implementation avoids unnecessary work in a dependency graph.

Here's what the graph looks like.

C ← A, B
D ← A, B
E ← C, A, D
F ← D, B
G ← C, E (only if C is falsy), D, F
H ← G
I ← G
J ← F
Enter fullscreen mode Exit fullscreen mode

A and B are the inputs. The expression that exposes unnecessary computation is G = C() + ( C() || E()%2 ) + D()[4].x + F(). When C() is truthy, G never reads E, so there's no need to evaluate it for G.

Here's the Solid 2 benchmark code.

const [A, setA] = createSignal(0)
const [B, setB] = createSignal(0)

createRoot(() => {
    const C = createMemo(() => (A() % 2) + (B() % 2))
    const D = createMemo(() => numbers.map(i => ({ x: i + (A() % 2) - (B() % 2) })), { equals })
    const E = createMemo(() => hard(C() + A() + D()[0].x, 'E'))
    const F = createMemo(() => hard(D()[2].x || B(), 'F'))
    const G = createMemo(() => C() + (C() || E() % 2) + D()[4].x + F())
    createEffect(G, g => {
        res.push(hard(g, 'H'))
    })
    createEffect(G, g => {
        res.push(g)
    })
    createEffect(F, f => {
        res.push(hard(f, 'J'))
    })
})

setB(1)
setA(1)
flush() // E and H are evaluated
setA(2)
setB(2)
flush() // E and H are evaluated
Enter fullscreen mode Exit fullscreen mode

Cold and hot runs are both measured in iterations per second.

Implementation Code size 🥶 Cold run 🥵 Hot run Memory
SolidJS 2 116 10,074 10,830 224–294
SolidJS 1 114 11,121 11,454 161–172
$mol_wire_solo 130 13,402 13,373 4–8
$mol_wire_let 96 13,955 13,897 3–5

Why the high memory usage? Both versions of Solid recompute E and H unnecessarily.

Here are the gzipped bundle sizes.

  • solid-js@2 — 49.7 KB, including 43.2 KB for @solidjs/signals. Remember, signals are everywhere now.
  • solid-js@1 — 8.6 KB.
  • mol_wire_lib — 8.9 KB.

So far, I'm underwhelmed. I wish the team had looked at what the best implementations already do before building their own reactivity system, if only to see what they could borrow. Before you come at me in the comments, hear me out. They've also decided to build a DSL. Yes, like view.tree in $mol. Ironic, isn't it? So far, they have two different prototypes.

Let's look at what else changed in Solid 2.

Async

Solid now makes everything that depends on a promise wait for it automatically.

function Profile(props) {
    const user = createMemo(() => fetchUser(props.id))
    return (
        <Loading fallback={<Skeleton />}>
            <div class={{ stale: isPending(() => user()) }}>{user().name}</div>
        </Loading>
    )
}
Enter fullscreen mode Exit fullscreen mode

$mol has worked this way from the start, going back ten years. You write the property synchronously, as if the data had already arrived.

export class $my_profile extends $.$my_profile {
    @$mol_mem
    user() {
        return this.$.$mol_fetch.json(`/api/user/${this.id()}`) as { name: string }
    }

    name() {
        return this.user().name
    }
}
Enter fullscreen mode Exit fullscreen mode
$my_profile $mol_view
    id \
    sub /
        <= name \
Enter fullscreen mode Exit fullscreen mode

The view shows its loading state automatically, so there's no need for a Loading component. Switching away from the screen also aborts the request.

Server Functions

I have to admit, I was baffled by this feature. The setup I'm used to is a backend with a Swagger/OpenAPI spec and client code generated from it.

After looking into it, I see the idea. Solid wants to be a full-stack framework, which means it needs a way to separate client and server code and support code that runs in both environments.

Here's how Solid does it.

'use server'
import { live } from '@solidjs/web/server-functions'

export const stockPrice = live(async function* (symbol) {
    for await (const tick of subscribe(symbol)) yield tick.price
})
Enter fullscreen mode Exit fullscreen mode
const price = createMemo(() => stockPrice(props.symbol))
Enter fullscreen mode Exit fullscreen mode

In $mol, filename suffixes specify whether a module is for the frontend, for the backend, or shared between them. A shared module can hold types used on both sides, for example.

In the same repository, you might have an api.node.ts file.

export class $my_api extends $mol_rest_resource {
    GET(msg: $mol_rest_message) {
        msg.reply({ path: msg.uri().pathname })
    }

    @$mol_mem
    price() {
        return $my_api_price.make({})
    }
}
$my_api.serve()
Enter fullscreen mode Exit fullscreen mode

Alongside it, you'd have api.web.ts or just api.ts. The client code looks the same as before.

export class $my_profile extends $.$my_profile {
    @$mol_mem
    user() {
        return this.$.$mol_fetch.json(`/api/user/${this.id()}`) as { name: string }
    }
}
Enter fullscreen mode Exit fullscreen mode

Or you can take it a step further. Define a table on the client, work with the data locally, and let the data sync automatically.

export class $my_stock extends $giper_baza_dict.with({
    Price: $giper_baza_atom_real,
}) {}
Enter fullscreen mode Exit fullscreen mode
stock() {
    return this.$.$giper_baza_glob.Pawn( this.link(), $my_stock )
}

price() {
    return this.stock().Price()?.val() ?? 0
}
Enter fullscreen mode Exit fullscreen mode

Diagnostics

Solid has added built-in support for agents and searchable error codes like this one.

[STRICT_READ_UNTRACKED] Reactive value read directly in an effect callback will not update.
  at src/Item.tsx:12:19
Enter fullscreen mode Exit fullscreen mode

$mol takes a simpler approach.

$bog_collider.Root(0).Case(3).sample()
Enter fullscreen mode Exit fullscreen mode

It uses human-readable, unique fully qualified names.

DSLs

ReactiveScript and TSRX are meant for agents, as I understand it. But what makes code easier for agents to write tends to make it easier for people to write, too.

In $mol, a view.tree file compiles to a typed TypeScript class.

$my_counter $mol_view
    sub /
        <= Value $mol_view
            sub / <= value? 0
        <= Inc $mol_button_minor
            title \+
            click? <=> inc? null
Enter fullscreen mode Exit fullscreen mode

The resulting class has Value(), value(), Inc(), and inc() properties. You add the behavior in .view.ts by overriding a method.

export class $my_counter extends $.$my_counter {
    inc() {
        this.value(this.value() + 1)
    }
}
Enter fullscreen mode Exit fullscreen mode

A subclass can override any nested property of any component with a single line, without passing props or forking the component. Solid is aiming for the same kind of built-in composition that $mol provides by default.

That's how the benchmark comparison tool is built. Three lines replace the deeply nested Source in $hyoo_js_perf.

$bog_collider $hyoo_js_perf
    Source $mol_link_source
        uri \https://github.com/b-on-g/collider
Enter fullscreen mode Exit fullscreen mode

Those Pesky Config Files

One thing I'm sure of is that nobody likes fiddling with config files. That's why $mol does away with them entirely. It uses conventions, like the filename suffixes for code that can run on the client, the server, or both.

Solid has jumped on the metaframework bandwagon.

npm create solid@latest
npm i @tanstack/solid-router @tanstack/solid-query
Enter fullscreen mode Exit fullscreen mode

I don't see the point of drawing a line between frameworks and metaframeworks.

API

I wrote about this in an earlier article. In React, you have to choose from twelve options. Solid has brought that down to two, which is great.

createEffect(
    () => count(),
    value => {
        console.log(value)
    },
)
Enter fullscreen mode Exit fullscreen mode
const states = createMemo( ()=> getStates( 'US' ) )
const [ state, setState ] = createSignal( '' )
const cities = createMemo( ()=> state() ? getCities( state() ) : [] )

<Loading fallback="Loading…">
    <select onChange={ e => setState( e.target.value ) }>
        <For each={ states() }>{ s => <option>{ s }</option> }</For>
    </select>
    <select disabled={ isPending( ()=> cities() ) }>
        <For each={ cities() }>{ c => <option>{ c }</option> }</For>
    </select>
</Loading>
Enter fullscreen mode Exit fullscreen mode

$mol also gives you just two options.

$my_geo $mol_list
    rows /
        <= State $mol_select
            value? <=> state? \
            options <= states /string
        <= City $mol_select
            value? <=> city? \
            options <= cities /string
Enter fullscreen mode Exit fullscreen mode
export class $my_geo extends $.$my_geo {
    states() {
        return this.$.$mol_fetch.json('/api/states?country=US') as string[]
    }

    cities() {
        if (!this.state()) return []
        return this.$.$mol_fetch.json(`/api/cities?state=${this.state()}`) as string[]
    }

    @$mol_mem
    city(next?: string) {
        this.state()
        return next ?? ''
    }
}
Enter fullscreen mode Exit fullscreen mode

Use @$mol_mem to memoize a method, or @$mol_action for an action such as handling a click.


There's plenty more I could say about $mol, of course. That's it for now. Follow my Telegram channel for more.

Top comments (0)