Solid is a reactive JavaScript UI library that does without a virtual DOM. Templates are compiled to real DOM nodes once, and updates run inside fine-grained reactions, so a state change executes only the code that depends on it. The split lets the compiler optimize first paint while the runtime optimizes updates, an emphasis that places Solid among the top-rated frameworks in the JS framework benchmark.
Installation and project setup
For JSX, install the package with npm:
npm install solid-js babel-preset-solid
Then register the preset in a Babel, webpack or Rollup config:
"presets": ["solid"]
A starter can also be scaffolded from the official templates:
# Create a small app from a Solid template
npx degit solidjs/templates/js my-app
# Change directory to the project created
cd my-app
# Install dependencies
npm i # or yarn or pnpm
# Start the dev server
npm run dev
TypeScript support exists; swap the first command's template path for npx degit solidjs/templates/ts my-app to start a TS project.
Rendering components
The component syntax is close to React, so it reads familiarly. Import render, define a component, and pass both the component and a container to render:
import { render } from "solid-js/web";
const HelloMessage = props => <div>Hello {props.name}</div>;
render(
() => <HelloMessage name="Taylor" />,
document.getElementById("hello-example")
);
The compiler turns this into real DOM expressions. The compiled output looks roughly like:
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")
);
The Solid Playground can show the compilation as well as several render modes: client-side, server-side, and client-side with hydration.
Signals: getters and setters
createSignal returns a pair of functions — a getter and a setter — rather than a value and its updater. The getter must be called explicitly so Solid can intercept the read and track it:
const [todos, addTodos] = createSignal([]);
Logging todos yields a function, not the value; use todos() to read it. A minimal list built on signals:
import { createSignal } from "solid-js";
const TodoList = () => {
let input;
const [todos, addTodos] = createSignal([]);
const addTodo = value => {
return addTodos([...todos(), value]);
};
return (
<section>
<h1>To do list:</h1>
<label for="todo-item">Todo item</label>
<input type="text" ref={input} name="todo-item" id="todo-item" />
<button onClick={() => addTodo(input.value)}>Add item</button>
<ul>
{todos().map(item => (
<li>{item}</li>
))}
</ul>
</section>
);
};
That renders a text field, and clicking "Add item" appends the new item and shows it in the list.
The getter-based model separates tracking from evaluation. In the following example, displayName and displayFullName are memos over two signals:
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);
The output is:
Create Signals
My name is Whitney Houston
Set showFullName: false
My name is Whitney
Change lastName
Set showFullName: true
My name is Whitney Boop
Notice that My name is ... does not log again after the last name is set. Nothing is currently listening to lastName(), so the new value of displayName() is only picked up when displayFullName() changes — which is why the fresh last name appears once setShowFullName becomes true again. The result is tighter, safer tracking of value updates.
Working with effects and memos
createEffect
createEffect tracks its dependencies and re-runs after any render in which one of them changed:
// Don't forget to import it first with 'import { createEffect } from "solid-js";'
const [count, setCount] = createSignal(0);
createEffect(() => {
console.log("Count is at", count());
});
Here Count is at... logs on every change to count().
createMemo
createMemo produces a read-only signal whose value recalculates whenever the dependencies of the executed code update. It is the tool for caching derived values that should not be recomputed until a dependency changes. A counter rendered 100 times, incremented on click, recalculates only once per click:
function Counter() {
const [count, setCount] = createSignal(0);
// Calling `counter` without wrapping it in `createMemo` would result in calling it 100 times.
// const counter = () => {
// return count();
// }
// Calling `counter` wrapped in `createMemo` results in calling it once per update.
// Don't forget to import it first with 'import { createMemo } from "solid-js";'
const counter = createMemo(() => {
return count()
})
return (
<>
<button onClick={() => setCount(count() + 1)}>Count: {count()}</button>
<div>1. {counter()}</div>
<div>2. {counter()}</div>
<div>3. {counter()}</div>
<div>4. {counter()}</div>
<!-- 96 more times -->
</>
);
}
Lifecycle hooks
Solid provides onMount, onCleanup and onError. Code that must run after the initial render belongs in onMount:
// Don't forget to import it first with 'import { onMount } from "solid-js";'
onMount(() => {
console.log("I mounted!");
});
onCleanup behaves like React's componentDidUnmount and fires when the reactive scope recalculates. onError runs when an error occurs in the nearest child scope — a failed data fetch, for instance.
Stores for structured state
createStore returns a readonly proxy object plus a setter function. Rewriting the todo example on a store gives:
const [todos, addTodos] = createStore({ list: [] });
createEffect(() => {
console.log(todos.list);
});
onMount(() => {
addTodos("list", [
...todos.list,
{ item: "a new todo item", completed: false }
]);
});
Two logs appear: a proxy wrapping an empty array, then a proxy wrapping an array holding {item: "a new todo item", completed: false}. Because the top-level state object is not itself trackable, a property must be accessed — log todos.list, not todos. Logging only todos inside createEffect would show the initial list but miss the update made in onMount. Mutations go through the setter produced by createStore, for example marking a list item completed:
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 helpers
Plain methods like .map() would rebuild all DOM nodes on each update, so Solid supplies template helpers instead: For iterates items, Show toggles visibility by condition, and Switch with Match renders the element matching a given condition, among others.
<For each={todos.list} fallback={<div>Loading...</div>}>
{(item) => <div>{item}</div>}
</For>
<Show when={todos.list[0].completed} fallback={<div>Loading...</div>}>
<div>1st item completed</div>
</Show>
<Switch fallback={<div>No items</div>}>
<Match when={todos.list[0].completed}>
<CompletedList />
</Match>
<Match when={!todos.list[0].completed}>
<TodosList />
</Match>
</Switch>
Trying it out
A starter project built around these concepts — the default Solid setup plus a sample todo app — can be deployed to Netlify and cloned to GitHub directly from the deploy button in the original article. The official docs cover considerably more of the framework.



