SolidJS: A high-performance responsive JavaScript UI library
Solid is a responsive JavaScript library for creating user interfaces, which does not require virtual DOM. It compiles the template into a real DOM node and wraps the updates in a fine-grained reaction, so when the state is updated, only the relevant code will run.
This method allows the compiler to optimize initial rendering and runtime updates. This focus on performance makes it one of the most acclaimed JavaScript frameworks.
I was curious about this and wanted to give it a try, so I spent some time creating a small to-do application to explore how this framework handles rendering components, updating state, setting up storage, and more.
If you can't wait to see the final code and results, check out the final demo: [The final demo link should be inserted here, not provided in the original text]
Quick Start
Like most frameworks, we can start by installing the npm package. To use the framework with JSX, run:
npm install solid-js babel-preset-solid
Then we need to add babel-preset-solid to our Babel, webpack or Rollup configuration file:
"presets": ["solid"]
Or, if you want to set up a small application, you can also use one of their templates:
# Create a small application from Solid template npx degit solidjs/templates/js my-app # Change to the created project directory cd my-app # Install dependencies npm i # or yarn or pnpm # Start the development server npm run dev
TypeScript is supported, if you want to start a TypeScript project, change the first command to npx degit solidjs/templates/ts my-app
.
Create and render components
The syntax of the rendering component is similar to React.js, so it may look familiar:
import { render } from "solid-js/web"; const HelloMessage = props =><div> Hello {props.name}</div> ; render( () =><hellomessage name="Taylor"></hellomessage> , document.getElementById("hello-example") );
We need to import the render function first, then create a div with text and prop, and call render, passing in the component and container elements.
This code is then compiled into a real DOM expression. For example, the above code example, once compiled by Solid, looks like this:
import { render, template, insert, createComponent } from "solid-js/web"; const _tmpl$ = template(`<div> Hello</div> `); const HelloMessage = props => { const _el$ = _tmpl$.cloneNode(true); insert(_el$, () => props.name); return _el$; }; render( () => createComponent(HelloMessage, { name: "Taylor" }), document.getElementById("hello-example") );
Solid Playground is very cool, it shows that Solid has different rendering methods, including client, server and client with hydration.
Use Signals to track changing values
Solid uses a hook called createSignal
, which returns two functions: a getter and a setter. This may look a little weird if you're used to using frameworks like React.js. You usually expect the first element to be the value itself; however, in Solid we need to explicitly call getters to intercept where the read value is located in order to keep track of its changes.
For example, if we are writing the following code:
const [todos, addTodos] = createSignal([]);
Recording todos
does not return a value, but a function. If we want to use the value, we need to call the function, such as todos()
.
For a small to-do list, this will be:
import { createSignal } from "solid-js"; const TodoList = () => { let input; const [todos, addTodos] = createSignal([]); const addTodo = value => { return addTodos([...todos(), value]); }; Return ( <h1 id="To-do-list">To do list:</h1> <input type="text" ref="{el"> input = el} /> <button onclick="{()"> addTodo(input.value)}>Add item</button>
-
{todos().map(item => (
- {item} ))}
The above code example will display a text field, and after clicking the "Add Project" button, the todos will be updated with the new project and it will be displayed in the list.
This may look very similar to using useState
, so what is the difference between using getter? Consider the following code example:
console.log("Create Signals"); const [firstName, setFirstName] = createSignal("Whitney"); const [lastName, setLastName] = createSignal("Houston"); const [displayFullName, setDisplayFullName] = createSignal(true); const displayName = createMemo(() => { if (!displayFullName()) return firstName(); return `${firstName()} ${lastName()}`; }); createEffect(() => console.log("My name is", displayName())); console.log("Set showFullName: false "); setDisplayFullName(false); console.log("Change lastName"); setLastName("Boop"); console.log("Set showFullName: true "); setDisplayFullName(true);
Running the above code will get:
<code>Create Signals My name is Whitney Houston Set showFullName: false My name is Whitney Change lastName Set showFullName: true My name is Whitney Boop</code>
The main point to note is that after setting a new lastName, "My name is..." is not recorded. This is because nothing is listening for changes to lastName()
at this point. The new value of displayFullName()
is set only when the value of displayName()
changes, which is why when setShowFullName
is set to true, we can see that the new lastName is displayed.
This provides us with a safer way to track updates of values.
Responsive primitives
In the last code example, I introduced createSignal
, and there are some other primitives: createEffect
and createMemo
.
createEffect
createEffect
tracks dependencies and runs after each rendering of the dependency changes.
// Don't forget to import it first using 'import { createEffect } from "solid-js";' const [count, setCount] = createSignal(0); createEffect(() => { console.log("Count is at", count()); });
Every time the value of count()
changes, "Count is at..." will be recorded
createMemo
createMemo
creates a read-only signal that recalculates its value whenever the dependencies of the executed code are updated. It can be used when you want to cache some values and access them without reevaluating them (until the dependency changes).
For example, if we want to display a counter 100 times and update the value when the button is clicked, using createMemo
will allow recalculation to occur only once per click:
function Counter() { const [count, setCount] = createSignal(0); // It will be called 100 times without creatingMemo wrapping counter // const counter = () => { // return count(); // } // Wrapping counter with createMemo, only called once per update // Don't forget to use 'import { createMemo } from "solid-js";' to import it const counter = createMemo(() => count()); Return ( <div> <button onclick="{()"> setCount(count() 1)}>Count: {count()}</button> <div>1. {counter()}</div> <div>2. {counter()}</div> <div>3. {counter()}</div> <div>4. {counter()}</div> </div> ); }
Lifecycle method
Solid exposes several lifecycle methods, such as onMount
, onCleanup
, and onError
. If we want some code to run after initial rendering, we need to use onMount
:
// Don't forget to import it first using 'import { onMount } from "solid-js";' onMount(() => { console.log("I mounted!"); });
onCleanup
is similar to componentDidUnmount
in React — it runs when responsive scope recalculation.
onError
is executed when an error occurs in the most recent subscope. For example, when the data acquisition fails, we can use it.
storage
To create a store for data, Solid exposes createStore
, whose return value is a read-only proxy object and a setter function.
For example, if we change our to-do example to use storage instead of state, it would look like this:
const [todos, addTodos] = createStore({ list: [] }); createEffect(() => { console.log(todos.list); }); onMount(() => { addTodos('list', (list) => [...list, { item: "a new todo item", completed: false }]); });
The above code example will first record a proxy object with an empty array, and then record a proxy object with an array containing the object {item: "a new todo item", completed: false}
.
It should be noted that if its properties are not accessed, the top-level state object cannot be tracked - that is why we log todos.list
instead of todos
.
If we only record todos
in createEffect
, we will see the initial value of the list, but we will not see the updated value in onMount
.
To change the values in the store, we can update them using the settings function defined when using createStore
. For example, if we want to update the to-do list item to "completed", we can update the storage this way:
const [todos, setTodos] = createStore({ list: [{ item: "new item", completed: false }] }); const markAsComplete = text => { setTodos( "list", (i) => i.item === text, "completed", (c) => !c ); }; Return ( <button onclick="{()"> markAsComplete("new item")}>Mark as complete</button> );
Control flow
To avoid wasting all DOM nodes are recreated every time they are updated when using methods like .map()
, Solid allows us to use the template assistant.
Some of these are available, such as For
for looping through projects, Show
for conditionally showing and hiding elements, Switch
and Match
for displaying elements that match specific conditions, and so on!
Here are some examples showing how to use them:
<for each="{todos.list}" fallback="{<div"> Loading... }> {(item) =><div> {item}</div> } </for> <show when="{todos.list[0]?.completed}" fallback="{<div"> Loading... }> <div>1st item completed</div> </show> <switch fallback="{<div"> No items }> <match when="{todos.list[0]?.completed}"><completedlist></completedlist></match> <match when="{!todos.list[0]?.completed}"><todolist></todolist></match> </switch>
Demo project
Here is a quick introduction to the basics of Solid. If you want to try it, I created a starter project that you can automatically deploy to Netlify and clone to your GitHub by clicking the button below!
[The button that is deployed to Netlify should be inserted here, not provided in the original text] This project includes the default settings for the Solid project, as well as an example to-do application for the basic concepts I mentioned in this post to help you get started!
This framework is much more than what I've covered here, so feel free to check out the documentation for more information!
The above is the detailed content of Introduction to the Solid JavaScript Library. For more information, please follow other related articles on the PHP Chinese website!

I recently found a solution to dynamically update the color of any product image. So with just one of a product, we can colorize it in different ways to show

In this week's roundup, Lighthouse sheds light on third-party scripts, insecure resources will get blocked on secure sites, and many country connection speeds

There are loads of analytics platforms to help you track visitor and usage data on your sites. Perhaps most notably Google Analytics, which is widely used

The document head might not be the most glamorous part of a website, but what goes into it is arguably just as important to the success of your website as its

What's happening when you see some JavaScript that calls super()?.In a child class, you use super() to call its parent’s constructor and super. to access its

JavaScript has a variety of built-in popup APIs that display special UI for user interaction. Famously:

I was chatting with some front-end folks the other day about why so many companies struggle at making accessible websites. Why are accessible websites so hard

There is an HTML attribute that does exactly what you think it should do:


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.