Home > Web Front-end > CSS Tutorial > Introduction to the Solid JavaScript Library

Introduction to the Solid JavaScript Library

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-03-20 09:42:17
Original
848 people have browsed it

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:

1

npm install solid-js babel-preset-solid

Copy after login

Then we need to add babel-preset-solid to our Babel, webpack or Rollup configuration file:

1

"presets": ["solid"]

Copy after login

Or, if you want to set up a small application, you can also use one of their templates:

1

2

3

4

5

6

7

# 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

Copy after login

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:

1

2

3

4

5

6

7

8

import { render } from "solid-js/web";

 

const HelloMessage = props =><div> Hello {props.name}</div> ;

 

render(

  () =><hellomessage name="Taylor"></hellomessage> ,

  document.getElementById("hello-example")

);

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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")

);

Copy after login

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:

1

const [todos, addTodos] = createSignal([]);

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import { createSignal } from "solid-js";

 

const TodoList = () => {

  let input;

  const [todos, addTodos] = createSignal([]);

 

  const addTodo = value => {

    return addTodos([...todos(), value]);

  };

 

  Return (

    <h1>To do list:</h1>

    <input type="text" ref="{el"> input = el} />

    <button onclick="{()"> addTodo(input.value)}>Add item</button>

Copy after login
    {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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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);

Copy after login

Running the above code will get:

1

<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>

Copy after login

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.

1

2

3

4

5

// 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());

});

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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>

  );

}

Copy after login

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 :

1

2

3

// Don't forget to import it first using 'import { onMount } from "solid-js";' onMount(() => {

  console.log("I mounted!");

});

Copy after login

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:

1

2

3

4

5

6

7

8

9

const [todos, addTodos] = createStore({ list: [] });

 

createEffect(() => {

  console.log(todos.list);

});

 

onMount(() => {

  addTodos('list', (list) => [...list, { item: "a new todo item", completed: false }]);

});

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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>

);

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

<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>

Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template