search
HomeWeb Front-endCSS TutorialIntroduction to the Solid JavaScript Library

SolidJS: A high-performance responsive JavaScript UI library

Introduction to the Solid JavaScript 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment