SolidJS - Everything You Need To Know

Solid JS takes the syntax and developer benefits of React and combines them with the overall performance of Svelte to offer you the best of both worlds.

Just like React, Solid uses JSX to render HTML within the browser. It also uses a similar syntax for reactivity to replace the DOM in real time. However, unlike React, it uses a compiled DOM rather than a virtual DOM.

In this manner, you get a smaller natural JavaScript package, much like the manufacturing bundle of your Svelte or Vanilla JS utility. This makes it blazingly fast and incredibly performant.

Solid Js; Source: LogInRadius

Features of Solid JS

Before you dive into the reading, let's show where Solid JS shines and the Solid JS tutorial. Here are the metrics published on the professional Internet Solid JS GitHub site.

Features of Solid JS; Source: LogInRadius

Components

The code in Solid JS is organized in a component-like structure. A component should generally constitute one part of the UI. A thing returns JSX (view to render). It can also comprise code to check in lifecycle and impact features and may include reactive statistics. A component is referred to as handiest once (not like React JS, in which components are re-accomplished as generally as state adjustments).

You can consider it a constructor feature. In the instance beneath, you can see a simple Solid JS app.

A simple Counter Component

// A Simple Component

const CounterComponent = () => {
// creates a reactive value, which is updated on UI
// returns getter/setter pair
const [count, setCount] = createSignal(0)

onMount(() => {
// Runs once when component is init
})

onCleanup(() => {
// Runs once when component is destroyed
})

createEffect(() => {
// called when count value is changed
console.log(count());
})

// mutates count + 1
const increase = () => setCount(count() + 1);

// mutates count -1
const decrease = () => setCount(count() - 1);

return (
<div>
{/* Displays count value */}
<div>Counter: {count()}</div>

{/* Calls increase on button click */}
<Button
onClick={increase}>Increase
</Button>
{/* Calls decrease on button click */}
<Button
onClick={decrease}>Decrease
</Button>
</div>
)
}

JSX

In Solid JS context, we can write the subsequent syntax:

const element = <h1>Hello, world!</h1>

You cannot write similar codes in regular JavaScript. This is called JSX, permitting us to write down JS code rendered as HTML inside the browser.

Lifecycle Functions

At the time of writing, Solid JS has three lifecycle features. They are very self-explanatory.

onMount(() => {
// Run once when the component is initialized. After the view is mounted.
})

onCleanup(() => {
// Run once when component is destroyed/recalculated
})

onError(() => {
// Run when children scope errors
})

Signals, Stores — Reactive Data

Solid JS tutorial: createSignal

The number one way to create reactive facts is to use the createSignal function.

const [count, setCount] = createSignal(0)

In the example above, createSignal(0) returns an array of two items. The first item is the getter characteristic, which returns the cost — it is more complex than the getter, but you can think of it like this for now.

If we call count, yes, you have got to call because it's a function.

// gets the value 0
count();

You get the value 0, which we provided as the default value.
The second item in the array is the setter function. To change the value, you call:
// sets the count to 100
setCount(100);

// returns 100
count();

If the value is changed, all of the references are updated in the UI without delay.

<div>
Current Count: {count()}
</div>

Solid JS tutorial: createStore

An alternative to createSignal is createStore, which is more suitable for dealing with objects and nested information.

An instance of this can be:

const [count, setCount] = createStore({value: 0, lastAction: "none"})
// count holds object -> {value: 0, lastAction: "none"}

This time you get the value and a setter function pair back.

To get the value

// gets the value 0
count.value;
// gets the value 'none'
count.lastAction;

To alternate the matter, provide the key of the object you need to alternate as the first parameter. The second parameter is the real value.

// sets the count value to 100
setCount("value", 100);
// returns 100
count.value;

// sets the count lastAction to 'increment'
setCount("lastAction", "increment");

// returns 'increment'
count.lastAction;

// Similarly, the UI is updated immediately.
<div>
Current Count: {count.value}
Last Action: {count.lastAction}
</div>

Solid JS vs. React: Why is SolidJS so fast?

Despite sharing nearly the same design philosophies, some capabilities set both JavaScript libraries apart. We will pass over some of those differences in this Solid js vs react section.

Solid JS vs React JS; Source: DevGenius

Absence of a digital DOM

One of the most noticeable differences in Solid js vs. react is the absence of a digital DOM. Contrary to the idea that the main DOM slows down software, it is part of what makes Solid so performant.

The digital DOM is a lightweight implementation of the principle DOM. In the future, JavaScript libraries will use the digital DOM as it becomes comparatively faster than the DOM itself. After all, the DOM was not constructed to handle frequent updates on a massive scale, so JavaScript libraries changed the virtual DOM, examined the modifications to the actual DOM, and merged them.

This is the solution that many libraries and frameworks, including React, Vue.js, and Riot.js, use; however, these days, the creators of Svelte and Solid have described the virtual DOM as pure overhead that only slows down the overall performance of the library. They have sought quicker options, including using the real DOM (which beats the relaxation of the virtual DOM opposition).

Solid achieves such performant speeds without using a digital DOM by combining its templates with actual DOM nodes and wrapping updates in excellent-grained reactions. In this manner, while your state updates, the code that relies on it runs.

Components don’t re-render

Components in Solid, unlike React, render just as soon as the JSX expressions and primitives that are being used within the aspect get updated. This brings performance gains to Solid, as re-rendering a factor is only vital; sometimes, it is used. Solid is reactive enough to track the modifications inside the issue.

Fine-grained reactivity

React isn't fully “reactive,” which the React crew acknowledges. This should no longer in any way be a turnoff for anyone looking to use React, as it still completes the tasks and is loved by lots of developers and businesses around the globe. However, Solid was built with reactivity in mind and used this as its promoting factor. It uses the term “fine-grained reactivity” to explain its performant speeds and potential to update facts swiftly.

How to apply CSS in Solid JS context

Some frameworks adjust the behavior of the <style> tags, but as a standards-based framework, in place of modifying behavior, we attempt to construct the pinnacle of it.

CSS in Solid JS; Source: freeCodeCamp

Styling components

Vite provides a simple way to control CSS for a complicated web app by permitting customers to import CSS using ESM syntax everywhere in the aspect tree. One feasible structure is to write CSS in a record accompanying your issue report. 90

src/

├── components/

│   ├── Button.tsx

│   ├── Button.css

Let's think we need to shade the buttons in our component blue. We can ordinarily fashion the button:

button {
background-color: #446b9e;
}
And then import our CSS file into the component:
import "./Button.css";
function Button(props) {
return <button>{props.text}</button>;
}

You may be aware that the CSS you simply imported is worldwide. This means that every button (now not just those created through this thing) might be blue! In many cases, global CSS is only sometimes the intended behavior. One easy solution is to make use of CSS features like magnificence selectors.

Typically, this would consist of adding a category to the basis detail, after which each CSS rule would be updated to use an infant selector. This works well for a small aspect, but for a complex one, adding a child selector to every CSS rule for the aspect can get tedious.

div.card {
background-color: #446b9e;
}
div.card > h1 {
}
div.card > p {
}

CSS Modules for scoped styles

SolidStart also supports Vite's CSS modules. Through CSS modules, you may scope positive CSS to a factor. This means that you could use the same CSS elegance in two additives, and style each of them differently.

To use the function, change the record extension from .Css to .Module.Css (or from .Scss or .Sass to .Module.Scss or .Module.Sass) and replace the import accordingly. You will observe that all at once your CSS stops operating!

This is because, behind the curtain, classes defined in the CSS module are being renamed to a chain of random letters. When we teach difficult code lessons using the magnificence characteristic (elegance= “card”), Solid does not know it has to rename card to something unique.

To repair this, you may import classes used for your CSS module. You can think of this import as a humanClass: generatedClass object. We reference the key (the class call we wrote) and get returned the particular, generated elegance name.

import styles from "./Card.module.css";
function Card(props) {
return <div class={styles.card}>{props.text}</div>;
}

Using Sass

You may also need to use the electricity of SCSS/Sass and different pre-processors. SCSS adds many low-cost CSS abstractions. Vite has first elegance assist for pre-processors, so to apply SCSS documents, definitely run:

npm add -D sass

Then trade the extension from .Css to .Scss and replace your imports accordingly.

Conclusion

Solid JS GitHub is a splendid library. It would be on the same level as React JS regarding programming experience. It's easy to apply, intuitive and gives lots of developer freedom. If you like more structured, completely functional frameworks like Angular JS, this library differs from what you're looking for.

Also, the ecosystem is currently quite small, so it can be more difficult to discover facts about Solid JS context online; however, this takes time to build. If you like JSX with a mixture of something new, give it a try.



How much is a great User Experience worth to you?


Browsee helps you understand your user's behaviour on your site. It's the next best thing to talking to them.

Browsee Product