Quick start

Introduction

Solid builds UIs with fine-grained reactivity: components run once and signals update the DOM. Covers Solid 2; see the 1.x migration guide.

Create an app

npm init solid@latest
npm run dev

Scaffolds a Solid 2 project with a Vite dev server.

See: Quick start

Render a component

import { render } from '@solidjs/web'

const dispose = render(
  () => <App />,
  document.getElementById('root')
)

Keep the disposer that render returns to unmount the tree.

See: render

A counter

const [count, setCount] = createSignal(0)

<button onClick={() => setCount(c => c + 1)}>
  Count: {count()}
</button>

Each JSX expression tracks its own reads; the component does not re-run.

See: Reactivity

Reactivity

Signals

const [count, setCount] = createSignal(0)
count()              // read
setCount(1)          // queue a write
setCount(c => c + 1) // updater
flush()              // apply now

Writes are staged; flush() applies them at once, which tests often need.

See: createSignal

Effects

createEffect(
  () => userId(),
  (id) => {
    const room = connect(id)
    return () => room.close()
  }
)

Only the compute function tracks reads; apply runs untracked after the flush.

See: createEffect

Memos

const total = createMemo(() =>
  items().reduce(
    (sum, x) => sum + x.price, 0
  )
)

Derives a cached value that updates when its reads change.

See: createMemo

Components and JSX

Props

function Greeting(props) {
  return <p>Hi {props.name}</p>
}

<Greeting name={user().name} />

Pass values, not accessors; destructuring props reads them once and breaks updates.

See: Props

Conditional classes

<button class={['btn', { active: isActive() }]}>
  Save
</button>

Objects toggle names; arrays combine names and objects. No classList in Solid 2.

See: Classes

Events and refs

let search
<input
  ref={el => (search = el)}
  onInput={e => setQuery(e.currentTarget.value)}
/>

Handlers are camelCase; native listener options need addEventListener in a ref.

See: Events and refs

Control flow

Conditions

<Show when={user()} fallback={<Login />}>
  {u => <Greeting name={u().name} />}
</Show>

The function child gets an accessor; keyed passes the value and remounts.

See: Show

Branching

<Switch fallback={<NotFound />}>
  <Match when={state() === 'loading'}>
    <Spinner />
  </Match>
  <Match when={state() === 'ready'}>
    <Page />
  </Match>
</Switch>

The first matching branch renders; fallback covers none.

See: Switch

Lists

<For
  each={todos()}
  fallback={<p>Empty</p>}
>
  {todo => <li>{todo.text}</li>}
</For>

Rows key by identity; keyed={false} gives an item accessor and stable index.

See: For

Stores

Create a store

const [cart, setCart] = createStore({
  items: []
})

setCart(draft => {
  draft.items.push({ id: 'mug', qty: 1 })
})

Each property tracks on its own. Read cart.items, not cart.items().

See: Stores

Update one property

setCart(draft => {
  const mug = draft.items.find(i => i.id === 'mug')
  if (mug) mug.qty = 2
})

Mutate the setter's draft; writing to the store proxy directly is ignored.

See: Update with a draft

Derived data

const visible = createProjection(
  () => cart.items.filter(i => !i.saved),
  []
)

Use a projection for derived objects and arrays; a memo for a single value.

See: createProjection

Async data

Fetch with a memo

Loading… Ada answer A Ada held · B loading id() changed Grace answer B
A changed input keeps A on screen until B arrives.
const user = createMemo(() => fetchUser(id()))

<Loading fallback={<Spinner />}>
  <Profile user={user()} />
</Loading>

Solid 2 replaced createResource: a memo can return a promise and reads suspend.

See: Async reactivity

Pending and errors

<Errored fallback={err => <p>{String(err())}</p>}>
  <p class={{ stale: isPending(user) }}>
    {user().name}
  </p>
</Errored>

isPending reports a held update; Errored catches a rejected read.

See: isPending

Refetch

const save = action(function* (name) {
  yield api.save(name)
  refresh(user)
})

A bare refresh is quiet; call affects(user) first to show pending state.

See: refresh

Routing

Define routes

export const Router = createRouter({
  routes: [
    { path: '/', component: lazy(() => import('./Home')) },
    { path: '/users/:id', component: User }
  ]
})
export const { paths } = Router

Define the tree once at module scope and build URLs with paths().

See: Solid Router

Read params

function User(props) {
  return <h1>{props.params.id}</h1>
}

Read params in JSX or a memo; the component does not re-run on navigation.

See: Read the URL

Load route data

Query

const getUser = query(
  id => fetch(`/api/users/${id}`).then(r => r.json()),
  'user'
)

Preload

{
  path: '/users/:id',
  component: User,
  preload: ({ params }) => void getUser(params.id)
}

preload runs when the route matches; preloadLinks: intentPreload() also starts it on hover. A page memo calling getUser(params.id) shares that cached entry.

See: Data loading

Integration

Custom elements

<date-picker
  value={date()}
  prop:disabledDates={holidays()}
  onDatechange={e => setDate(e.detail.value)}
/>

Plain attributes are strings; prop: assigns a property, and onXxx listens for lowercase custom events.

See: Web components

Server functions

async function getUser(id) {
  'use server'
  return db.users.find(id)
}

The function body stays on the server; call it from a memo in a component.

See: Server functions

Server components (experimental)

const Thread = dynamicComponent(() => getThread())

<Thread id={id()} />

A server function can return a component reference; Solid mounts it in place.

See: Durable generation

Also see

0 Comments for this cheatsheet. Write yours!