What is solid-js?
Solid.js is a declarative JavaScript library for building user interfaces. It focuses on fine-grained reactivity, which allows for highly efficient updates and minimal re-renders. Solid.js is designed to be fast and simple, providing a reactive programming model that is easy to understand and use.
What are solid-js's main functionalities?
Reactive State Management
Solid.js uses fine-grained reactivity for state management. The `createSignal` function creates a reactive state that updates the UI efficiently when the state changes.
import { createSignal } from 'solid-js';
function Counter() {
const [count, setCount] = createSignal(0);
return (
<div>
<button onClick={() => setCount(count() + 1)}>Increment</button>
<p>Count: {count()}</p>
</div>
);
}
JSX Support
Solid.js supports JSX, allowing you to write HTML-like syntax within JavaScript. This makes it easy to create and manage UI components.
import { render } from 'solid-js/web';
function App() {
return (
<div>
<h1>Hello, Solid.js!</h1>
</div>
);
}
render(() => <App />, document.getElementById('root'));
Component Composition
Solid.js allows for easy component composition. You can create reusable components and pass data to them via props.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Greeting name="Solid.js" />
</div>
);
}
Direct DOM Manipulation
Solid.js provides direct DOM manipulation capabilities. The `onCleanup` function allows you to perform cleanup tasks, such as clearing intervals, when a component is unmounted.
import { onCleanup } from 'solid-js';
function Timer() {
let timerId;
const [time, setTime] = createSignal(0);
const startTimer = () => {
timerId = setInterval(() => setTime(time() + 1), 1000);
};
onCleanup(() => clearInterval(timerId));
return (
<div>
<p>Time: {time()}</p>
<button onClick={startTimer}>Start Timer</button>
</div>
);
}
Other packages similar to solid-js
react
React is a popular JavaScript library for building user interfaces. It uses a virtual DOM and a component-based architecture. Compared to Solid.js, React has a larger ecosystem and community but may have more overhead due to its virtual DOM.
vue
Vue.js is a progressive JavaScript framework for building user interfaces. It features a reactive data binding system and a component-based architecture. Vue.js is similar to Solid.js in its reactivity model but offers more built-in features and a larger ecosystem.
svelte
Svelte is a compiler that converts declarative components into efficient imperative code that directly manipulates the DOM. Unlike Solid.js, Svelte does not use a virtual DOM and compiles components at build time, resulting in highly optimized and fast applications.
Solid.js
Solid.js is yet another declaritive Javascript library for creating user interfaces. It does not use the Virtual DOM. Instead it opts to compile it's templates down to real DOM nodes and wrap updates in fine grained computations.
Key Features:
- Real DOM with fine grained change detection (No Virtual DOM! No Dirty Checking Digest Loop!)
- JSX precompilation with support for standard JSX features and W3C Web Components
- Declarative data
- Data behavior is part of the declaration
- No need for lifecycle functions, and the large chains of conditionals they bring.
- ES6 Proxies to keep data access simple and POJO like
- Expandable custom operators and binding directives.
- Immutable interface with performance of mutability.
- Performance amongst the fastest libraries. See Solid on JS Framework Benchmark
A Simple Component could look like:
import { root } from 'solid-js'
const MyComponent = props =>
<>
<h1>Welcome</h1>
<p>Hello {props.name}</p>
</>
root(() => mountEl.appendChild(<MyComponent name='Taylor' />));
Installation
> npm install solid-js s-js babel-plugin-jsx-dom-expressions
Solid State
It all starts with a State object. These objects can represent the local state or the props in your components. State objects look like plain javascript options except to control change detection you call their setter method. They give the control of an immutable interface and the performance of a mutable one.
import { root, useState } from 'solid-js'
const CountingComponent = () => {
const [state, setState] = useState({counter: 0}),
interval = setInterval(() => setState({
counter: state.counter + 1
}), 1000);
useCleanup(() => clearInterval(interval));
return <div>{state.counter}</div>
}
You can also deep set:
const [state, setState] = useState({
user: {
firstName: 'John'
lastName: 'Smith'
}
});
setState('user', {firstName: 'Jake', middleName: 'Reese'});
You can also use functions:
const [state, setState] = useState({counter: 0});
setState('counter', c => c + 1);
This takes the form similar to ImmutableJS for set and setIn leaving all mutation control at the top level state object.
But where the magic happens is with computations(effects and memos) which automatically track dependencies.
useEffect(() => setState({
displayName: `${state.user.firstName} ${state.user.lastName}`
}));
console.log(state.displayName);
Whenever any dependency changes the State value will immediately update. Internally all JSX expressions also get wrapped in effects so for something as trivial as a display name you could just inline the expression in the template and have it update automatically.
This is also primary mechanism to interopt with store technologies like Redux, Apollo, RxJS which expose themselves as Observables or Promises. When you hook up these effects you can use standard methods to map the properties you want and the reconcile method will diff the changes to only affect the minimal amount.
useEffect(() => {
const disposable = store.observable()
.subscribe(({ todos }) => setState(reconcile('todos', todos)));
useCleanup(() => disposable.unsubscribe());
});
Solid Rendering
To accomplish rendering we use JSX for templating that gets compiled to native DOM element instructions. To do that we take advantage of the babel-plugin-jsx-dom-expressions which while converting JSX to DOM element instructions wraps expressions to be wrapped in our computeds.
JSX as a templating language brings a lot of benefits. The just being javascript goes beyond just not needing a DSL, but setting up closure based context instead of creating context objects. This is more transparent and easier to follow and debug.
To get setup add this babel plugin config to your .babelrc, webpack, or rollup config:
"plugins": ["jsx-dom-expressions"]
And include at the top of your files:
import { r } from 'solid-js/dom'
Components
Templates in Solid are just Pascal(Capital) cased functions. Their first argument is an props object and generally return their DOM nodes to render. Other than that nothing is special about them. Unlike Virtual Dom libraries these functions can contain state as they are not called repeatedly but only executed on initial creation.
Since the all nodes from JSX are actual DOM nodes the only responsibility of top level Templates/Components is appending to the DOM. Since contexts/lifecycle management is independent of code modularization through registering event handlers Solid Templates are sufficient as is to act as Components, or Solid fits easily into other Component structures like Web Components.
import { useState, root } from 'solid-js'
class Component extends HTMLElement {
constructor () {
const [state, setState] = useState({}),
[props, __setProps] = useState({});
Object.assign(this, {state, setState, props, __setProps});
}
connectedCallback() {
this.attachShadow({mode: 'open'});
root(() => this.shadowRoot.appendChild(this.render());
}
attributeChangedCallback(attr, oldVal, newVal) {
this.__setProps({[attr]: newVal});
}
}
class MyComponent extends Component {
constuctor () {
super();
this.setState({greeting: 'World'});
}
render() {
return <div>Hello {(state.greeting)}</div>
}
}
Why?
This project started as trying to find a small performant library to work with Web Components, that had easy interopt with existing standards. It is very inspired by fine grain change detection libraries like Knockout.js and RxJS. The idea here is to ease users into the world of Observable programming by keeping it transparent and starting simple. Classically the Virtual DOM as seen in React for all it's advances has some signifigant trade offs:
- The VDOM render while performant is still conceptually a constant re-render
- It feels much more imperative as variable declarations and iterative methods for constructing the tree are constantly re-evaluating.
- Reintroduced lifecycle function hell that break apart the declarative nature of the data. Ex. relying on blacklisting changes across the tree with shouldComponentUpdate.
- Homogenous promise of Components and the overly simplistic local state in practice:
- Imposes boundaries on components to solve performance concerns
- Prices you into a very specific but not necessarily obvious structure
- Only served to make it more ambiguous when emerging best practices lead to specialized component classification anyway
- Abstracts debugging to the point a
<div />
is not longer just a div - VDOM libraries still are based around having a specialized data objects.
So the driving questions here are:
- If the data is going to be specialized anyway can we use Proxies to move the complexity into it rather than the rendering while keeping the appearance simple?
- Can this free up existing constraints on how you modularize your view code?
- Does this approach ultimately provide more adaptibility while reducing the API surface?
- Is fine grained change detection fundamentally more performant than the Virtual DOM?
Admittedly it takes a strong reason to not go with the general consensus of best, and most supported libraries and frameworks. And React's Hooks API addresses the majority of what I once considered it's most untenable faults. But I believe there is a better way out there than how we do it today.
Documentation
Examples
Related Projects
- babel-plugin-jsx-dom-expressions
The renderer behind Solid.js that enables lightning fast fine grained performance.
- S.js The fine grained change detection engine that drives all computations and tracks all dependencies.
- React Solid State
A local state swap in for React to use Solid.js paradigm in your existing React apps.
- Solid Components
Extensions to Solid.js that add a Web Component wrapper, Portals, and a Context API.
Status
This project is still a work in progress. Do not use in production. I am still refining the API.