コンテンツにスキップ

SolidJS

仮想DOMを使わない、きめ細かいリアクティブJavaScript UIフレームワークで、卓越したパフォーマンスを実現。

コマンド説明
npx degit solidjs/templates/ts my-appTypeScript SolidJSプロジェクトを作成
npx degit solidjs/templates/js my-appJavaScript SolidJSプロジェクトを作成
npm create solid@latestSolidStart CLIでプロジェクトを作成
npm install solid-js既存プロジェクトにSolidJSをインストール
npm install solid-startSolidStartメタフレームワークをインストール
コマンド説明
npm run devホットリロード付きの開発サーバーを起動
npm run build本番用にビルド
npm run serve本番ビルドをローカルでプレビュー
npm run startSolidStartサーバーを起動
# 基本SolidJS(Vite)
npx degit solidjs/templates/ts my-app
cd my-app && npm install

# SolidStart(フルスタックメタフレームワーク)
npm create solid@latest my-app
# テンプレートを選択: bare, with-auth, with-mdx, with-prisma, with-tailwindcss

# コミュニティテンプレート
npx degit solidjs/templates/ts-windicss my-app    # WindiCSS
npx degit solidjs/templates/ts-unocss my-app      # UnoCSS
npx degit solidjs/templates/ts-bootstrap my-app    # Bootstrap
npx degit solidjs/templates/ts-sass my-app         # Sass
コマンド説明
function App() { return <div>Hello</div> }基本コンポーネントを定義
<MyComponent name="value" />コンポーネントにpropsを渡す
props.children子コンテンツにアクセス
<div class={styles.container}>CSSクラスを適用(classNameではなくclassを使用)
<div classList={{ active: isActive() }}>条件付きCSSクラス
<div style={{ color: 'red', 'font-size': '14px' }}>インラインスタイルを適用
<div innerHTML={htmlString} />生のHTMLコンテンツを設定
<div ref={myRef}>DOM参照をアタッチ
コマンド説明
<div onClick={handler}>委譲イベントをアタッチ
<div on:click={handler}>ネイティブDOMイベントをアタッチ(委譲をバイパス)
<div onInput={(e) => setValue(e.target.value)}>入力イベントを処理
<div on:keydown={(e) => handleKey(e)}>キーボードイベントをネイティブに処理
<div onClick={[handler, data]}>イベントハンドラにデータを渡す
import { type Component, type ParentComponent } from 'solid-js'

// 型付きコンポーネントとprops
interface UserProps {
  name: string
  age: number
  role?: string
}

const UserCard: Component<UserProps> = (props) => {
  return (
    <div class="card">
      <h2>{props.name}</h2>
      <p>Age: {props.age}</p>
      <p>Role: {props.role ?? 'Member'}</p>
    </div>
  )
}

// 親コンポーネント(子を受け入れる)
const Layout: ParentComponent = (props) => {
  return (
    <div class="layout">
      <header>My App</header>
      <main>{props.children}</main>
      <footer>Footer</footer>
    </div>
  )
}

// propsの分割とフォワーディング
import { splitProps } from 'solid-js'

const Button: Component<ButtonProps> = (props) => {
  const [local, rest] = splitProps(props, ['variant', 'size'])
  return (
    <button
      class={`btn btn-${local.variant} btn-${local.size}`}
      {...rest}
    />
  )
}

// デフォルトpropsのマージ
import { mergeProps } from 'solid-js'

const Alert: Component<AlertProps> = (rawProps) => {
  const props = mergeProps({ type: 'info', dismissible: false }, rawProps)
  return <div class={`alert alert-${props.type}`}>{props.children}</div>
}
コマンド説明
const [count, setCount] = createSignal(0)リアクティブシグナルを作成
count()シグナル値を読み取り(関数として呼び出す必要あり)
setCount(5)シグナルを特定の値に設定
setCount(prev => prev + 1)前の値を使ってシグナルを更新
const [name, setName] = createSignal<string>()型付きシグナルを作成
コマンド説明
createEffect(() => console.log(count()))シグナル変更時に副作用を実行
createEffect(on(count, (v) => log(v)))特定のシグナルを明示的に追跡
createEffect(on([a, b], ([a, b]) => ...))複数のシグナルを明示的に追跡
const double = createMemo(() => count() * 2)派生/計算値を作成
createRenderEffect(() => ...)DOM描画前に実行されるエフェクト
createComputed(() => ...)レンダリング中の同期エフェクト
コマンド説明
onMount(() => { ... })コンポーネントのマウント時に一度実行
onCleanup(() => { ... })コンポーネントのアンマウント時にクリーンアップを実行
batch(() => { setA(1); setB(2) })複数のシグナル更新をバッチ処理
untrack(() => value())依存関係の追跡なしでシグナルを読み取り
import { createSignal, createEffect, createMemo, on, batch, untrack } from 'solid-js'

function Counter() {
  const [count, setCount] = createSignal(0)
  const [step, setStep] = createSignal(1)

  // 派生値(メモ化、countが変わったときのみ再計算)
  const doubled = createMemo(() => count() * 2)
  const isEven = createMemo(() => count() % 2 === 0)

  // エフェクト: アクセスされたシグナルが変わると実行
  createEffect(() => {
    console.log(`Count is now: ${count()}`)
    // count()を依存関係として自動追跡
  })

  // on()による明示的な追跡
  createEffect(on(count, (value, prev) => {
    console.log(`Changed from ${prev} to ${value}`)
  }, { defer: true })) // defer: 初回実行をスキップ

  // バッチ更新(単一の再レンダリング)
  const reset = () => batch(() => {
    setCount(0)
    setStep(1)
  })

  // 依存関係を作らずに読み取り
  const logWithoutTracking = () => {
    const current = untrack(() => count())
    console.log('Snapshot:', current)
  }

  return (
    <div>
      <p>Count: {count()} (doubled: {doubled()}, even: {String(isEven())})</p>
      <button onClick={() => setCount(c => c + step())}>
        Add {step()}
      </button>
      <button onClick={reset}>Reset</button>
    </div>
  )
}
コマンド説明
<Show when={loggedIn()} fallback={<Login/>}>条件付きレンダリング
<For each={items()}>{(item) => <li>{item}</li>}</For>リストをレンダリング(参照でキー付け)
<Index each={items()}>{(item, i) => <li>{item()}</li>}</Index>リストをレンダリング(インデックスでキー付け)
<Switch><Match when={a()}>A</Match></Switch>Switch/caseレンダリング
<ErrorBoundary fallback={err => <p>{err}</p>}>レンダーエラーをキャッチ
<Suspense fallback={<Loading/>}>非同期読み込み中にフォールバックを表示
<Dynamic component={MyComp} />動的コンポーネントをレンダリング
<Portal mount={document.body}>別のDOMノードにレンダリング
import { Show, For, Index, Switch, Match, Suspense, ErrorBoundary } from 'solid-js'

function Dashboard() {
  const [user, setUser] = createSignal(null)
  const [items, setItems] = createSignal([
    { id: 1, name: 'Alpha', status: 'active' },
    { id: 2, name: 'Beta', status: 'inactive' },
  ])
  const [view, setView] = createSignal('list')

  return (
    <div>
      {/* Show: フォールバック付きの条件付きレンダリング */}
      <Show when={user()} fallback={<p>Please log in</p>}>
        {(u) => <p>Welcome, {u().name}!</p>}
      </Show>

      {/* For: 参照によるキー付け(オブジェクトに最適) */}
      <For each={items()}>
        {(item, index) => (
          <div>
            <span>{index() + 1}. {item.name}</span>
            <span> ({item.status})</span>
          </div>
        )}
      </For>

      {/* Switch/Match: 複数の条件 */}
      <Switch fallback={<p>Unknown view</p>}>
        <Match when={view() === 'list'}>
          <ListView />
        </Match>
        <Match when={view() === 'grid'}>
          <GridView />
        </Match>
        <Match when={view() === 'table'}>
          <TableView />
        </Match>
      </Switch>

      {/* ErrorBoundary: 子ツリーのエラーをキャッチ */}
      <ErrorBoundary fallback={(err, reset) => (
        <div>
          <p>Error: {err.message}</p>
          <button onClick={reset}>Try Again</button>
        </div>
      )}>
        <RiskyComponent />
      </ErrorBoundary>
    </div>
  )
}
コマンド説明
const [store, setStore] = createStore({})リアクティブストアを作成
setStore('name', 'Alice')パスでストアプロパティを更新
setStore('users', 0, 'name', 'Bob')ネストされたストアプロパティを更新
setStore('list', l => [...l, item])ストア配列にアイテムを追加
setStore('list', i => i.id === 1, 'done', true)条件に合致する配列アイテムを更新
produce(s => { s.count++ })ミュータブルスタイルのストア更新
reconcile(newData)ストアデータを効率的に置換
unwrap(store)生のプロキシされていないデータを取得
import { createStore, produce, reconcile, unwrap } from 'solid-js/store'

interface Todo {
  id: number
  text: string
  completed: boolean
}

interface AppState {
  todos: Todo[]
  filter: 'all' | 'active' | 'completed'
  user: { name: string; settings: { theme: string } }
}

function TodoApp() {
  const [state, setState] = createStore<AppState>({
    todos: [],
    filter: 'all',
    user: { name: 'Alice', settings: { theme: 'dark' } },
  })

  // アイテム追加
  const addTodo = (text: string) => {
    setState('todos', todos => [
      ...todos,
      { id: Date.now(), text, completed: false }
    ])
  }

  // マッチングによる特定アイテムのトグル
  const toggleTodo = (id: number) => {
    setState('todos', todo => todo.id === id, 'completed', c => !c)
  }

  // アイテム削除(filterで新しい配列を生成)
  const deleteTodo = (id: number) => {
    setState('todos', todos => todos.filter(t => t.id !== id))
  }

  // produceによるミュータブルスタイルの更新
  const clearCompleted = () => {
    setState(produce((s) => {
      s.todos = s.todos.filter(t => !t.completed)
    }))
  }

  // 深いネストの更新
  const setTheme = (theme: string) => {
    setState('user', 'settings', 'theme', theme)
  }

  // ストアデータ全体の置換(reconcileで効率的に差分)
  const loadFromServer = async () => {
    const data = await fetch('/api/todos').then(r => r.json())
    setState('todos', reconcile(data))
  }

  return (/* ... */)
}
コマンド説明
const [data] = createResource(fetchFn)非同期リソースを作成
const [data] = createResource(id, fetchFn)リアクティブソースシグナル付きリソース
data()リソースデータにアクセス
data.loadingリソースが読み込み中か確認
data.errorリソースエラーにアクセス
data.latest最後に解決された値を取得(再取得後も保持)
data.stateリソースの状態を取得(‘unresolved’, ‘pending’, ‘ready’, ‘errored’)
const { refetch } = data手動で再取得をトリガー
createResource(source, fetcher, { initialValue })初期値付きリソース
import { createResource, createSignal, Suspense, ErrorBoundary } from 'solid-js'

interface User {
  id: number
  name: string
  email: string
}

async function fetchUser(id: number): Promise<User> {
  const res = await fetch(`/api/users/${id}`)
  if (!res.ok) throw new Error(`User ${id} not found`)
  return res.json()
}

function UserProfile() {
  const [userId, setUserId] = createSignal(1)

  // userId()が変わると自動的に再取得
  const [user, { refetch, mutate }] = createResource(userId, fetchUser)

  // 楽観的更新
  const updateName = async (newName: string) => {
    const prev = user()
    mutate({ ...prev!, name: newName }) // 楽観的
    try {
      await fetch(`/api/users/${userId()}`, {
        method: 'PATCH',
        body: JSON.stringify({ name: newName }),
      })
    } catch {
      mutate(prev) // エラー時にロールバック
    }
  }

  return (
    <ErrorBoundary fallback={<p>Failed to load user</p>}>
      <Suspense fallback={<p>Loading user...</p>}>
        <div>
          <h2>{user()?.name}</h2>
          <p>{user()?.email}</p>
          <p>State: {user.state}</p>
          <button onClick={refetch} disabled={user.loading}>
            Refresh
          </button>
          <button onClick={() => setUserId(id => id + 1)}>
            Next User
          </button>
        </div>
      </Suspense>
    </ErrorBoundary>
  )
}
コマンド説明
npm install @solidjs/routerSolidJSルーターをインストール
<Router><Route path="/" component={Home}/></Router>基本ルートを定義
<Route path="/users/:id" component={User}/>パラメータ付きルート
<Route path="/*all" component={NotFound}/>キャッチオールルート
const params = useParams()ルートパラメータにアクセス
const [searchParams, setSearchParams] = useSearchParams()クエリパラメータにアクセス
const navigate = useNavigate()プログラムによるナビゲーション
navigate('/dashboard')パスにナビゲート
<A href="/about">About</A>ナビゲーションリンクコンポーネント
<A href="/about" activeClass="active">アクティブスタイル付きリンク
import { Router, Route, A, useParams, useNavigate, useSearchParams } from '@solidjs/router'
import { lazy } from 'solid-js'

// 遅延読み込みルート
const Dashboard = lazy(() => import('./pages/Dashboard'))
const UserProfile = lazy(() => import('./pages/UserProfile'))
const Settings = lazy(() => import('./pages/Settings'))

function App() {
  return (
    <Router>
      <nav>
        <A href="/" activeClass="active" end>Home</A>
        <A href="/dashboard" activeClass="active">Dashboard</A>
        <A href="/settings" activeClass="active">Settings</A>
      </nav>
      <Route path="/" component={Home} />
      <Route path="/dashboard" component={Dashboard} />
      <Route path="/users/:id" component={UserProfile} />
      <Route path="/settings" component={Settings} />
      <Route path="/*all" component={NotFound} />
    </Router>
  )
}

// ネストされたルート
function App() {
  return (
    <Router>
      <Route path="/admin" component={AdminLayout}>
        <Route path="/" component={AdminDashboard} />
        <Route path="/users" component={AdminUsers} />
        <Route path="/users/:id" component={AdminUserDetail} />
      </Route>
    </Router>
  )
}
import { createContext, useContext, type ParentComponent } from 'solid-js'
import { createStore } from 'solid-js/store'

interface AuthState {
  user: { name: string; role: string } | null
  token: string | null
}

interface AuthContextValue {
  state: AuthState
  login: (token: string, user: AuthState['user']) => void
  logout: () => void
  isAuthenticated: () => boolean
}

const AuthContext = createContext<AuthContextValue>()

const AuthProvider: ParentComponent = (props) => {
  const [state, setState] = createStore<AuthState>({
    user: null,
    token: null,
  })

  const value: AuthContextValue = {
    state,
    login: (token, user) => {
      setState({ token, user })
    },
    logout: () => {
      setState({ token: null, user: null })
    },
    isAuthenticated: () => state.token !== null,
  }

  return (
    <AuthContext.Provider value={value}>
      {props.children}
    </AuthContext.Provider>
  )
}

function useAuth() {
  const context = useContext(AuthContext)
  if (!context) throw new Error('useAuth must be used within AuthProvider')
  return context
}

// 使用例
function UserMenu() {
  const auth = useAuth()
  return (
    <Show when={auth.isAuthenticated()} fallback={<LoginButton />}>
      <p>Hello, {auth.state.user?.name}</p>
      <button onClick={auth.logout}>Logout</button>
    </Show>
  )
}
コマンド説明
import styles from './App.module.css'CSSモジュールをインポート
<div class={styles.container}>CSSモジュールクラスを適用
npm install solid-styled-componentsSolid用styled-componentsをインストール
const Btn = styled('button')\color: red“スタイル付きコンポーネントを作成
<div class="static-class">静的CSSクラスを適用
# Tailwind CSSをインストール
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
// tailwind.config.js
export default {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: { extend: {} },
  plugins: [],
}
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

SolidStart(メタフレームワーク)

Section titled “SolidStart(メタフレームワーク)”
コマンド説明
npm create solid@latestSolidStartプロジェクトを作成
"use server" ディレクティブ関数をサーバー専用としてマーク
createServerAction$()サーバーアクションを作成
createRouteData()サーバー上でルートのデータを読み込み
<Title>Page Title</Title>ページタイトルを設定(@solidjs/metaから)
<Meta name="description" content="..." />メタタグを設定
// src/routes/todos.tsx
import { createAsync, query, action, redirect } from '@solidjs/router'

// サーバークエリ(データ読み込み)
const getTodos = query(async () => {
  'use server'
  const db = await getDatabase()
  return db.todos.findMany()
}, 'todos')

// サーバーアクション(ミューテーション)
const addTodo = action(async (formData: FormData) => {
  'use server'
  const text = formData.get('text') as string
  const db = await getDatabase()
  await db.todos.create({ data: { text, completed: false } })
  throw redirect('/todos') // 再検証
})

export default function TodosPage() {
  const todos = createAsync(() => getTodos())

  return (
    <div>
      <form action={addTodo} method="post">
        <input name="text" placeholder="New todo" required />
        <button type="submit">Add</button>
      </form>
      <Suspense fallback={<p>Loading...</p>}>
        <For each={todos()}>
          {(todo) => <p>{todo.text}</p>}
        </For>
      </Suspense>
    </div>
  )
}
npm install -D vitest @solidjs/testing-library @testing-library/jest-dom jsdom
npm install -D vite-plugin-solid
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import solid from 'vite-plugin-solid'

export default defineConfig({
  plugins: [solid()],
  test: {
    environment: 'jsdom',
    globals: true,
    setupFiles: './src/test-setup.ts',
    transformMode: { web: [/\.[jt]sx?$/] },
  },
})
import { render, screen, fireEvent } from '@solidjs/testing-library'
import { describe, it, expect } from 'vitest'
import Counter from './Counter'

describe('Counter', () => {
  it('renders initial count', () => {
    render(() => <Counter initialCount={5} />)
    expect(screen.getByText('Count: 5')).toBeInTheDocument()
  })

  it('increments on click', async () => {
    render(() => <Counter initialCount={0} />)
    const button = screen.getByRole('button', { name: /increment/i })
    fireEvent.click(button)
    expect(screen.getByText('Count: 1')).toBeInTheDocument()
  })
})
  1. シグナルは常に関数として呼び出すcountではなくcount()。括弧を忘れるのはSolidJSで最も一般的なミスです。括弧なしでは値の代わりにゲッター関数を渡してしまいます。

  2. propsを分割代入しない — 分割代入は値を一度だけ読み取るためリアクティビティが壊れます。props.nameを直接使用するか、props操作にはsplitProps()/mergeProps()を使用してください。

  3. オブジェクト配列には<For>、プリミティブには<Index>を使用<For>は参照でキー付け(並べ替えられる可能性のあるオブジェクトに最適)、<Index>は位置でキー付け(単純な値リストに最適)します。

  4. 複雑な状態にはストアを使用 — シグナルは単純な値に最適ですが、ネストされたオブジェクトや配列にはcreateStoreがオブジェクト全体を置換せずにきめ細かいリアクティビティを提供します。

  5. 明示的な追跡にはon()を使用 — エフェクト内で読み取られるすべてのシグナルではなく特定のシグナルのみを追跡したい場合、on(signal, callback)でラップします。

  6. SuspenseErrorBoundaryを活用 — 非同期コンポーネントは読み込み状態のためにSuspenseで、エラーのグレースフルハンドリングのためにErrorBoundaryでラップします。

  7. ルートは遅延読み込みする — ルートコンポーネントにはlazy(() => import('./Page'))を使用してコード分割を有効にし、初期バンドルサイズを削減します。

  8. 複数の更新にはbatch()を使用 — 複数のシグナルを一度に設定する場合、batch()でラップして複数ではなく単一の再レンダリングをトリガーします。

  9. コンポーネントは小さく保つ — SolidJSのコンポーネントは本体を一度だけ実行します(Reactのように毎回レンダリングしない)。大きなコンポーネントは分割してリアクティブ更新のスコープを制限しましょう。

  10. シグナルにはTypeScriptジェネリクスを使用createSignal<string | null>(null)はリアクティブ状態に対してより良い型安全性と自動補完を提供します。

  11. コンパイルモデルを理解する — SolidJSはビルド時にJSXを実際のDOM操作にコンパイルします。仮想DOMの差分はないため、高速ですが、リアクティビティのルール(分割代入しない、シグナルを呼び出す)が重要です。

  12. untrack()は控えめに使用untrack()内でシグナルを読み取ると依存関係の追跡が防がれます。ログや一度きりの読み取りには便利ですが、多用するとバグの原因になります。