geekskai Logogeekskai
ToolsBlogPricing
Sign in
Sign in
ToolsBlogSign in
Monday, February 3, 2025|6.985Mins Read

Mastering React SWR Vite Integration

Authors
  • avatar
    Name
    Geeks Kai
    Twitter
    @KaiGeeks
Discuss on Twitter • View on GitHub

Tags

reactswrvitedata-fetchingweb-developmentReact-SWR-Vite

Previous Article

Expo SQLite and TanStack Query v5: Local Tasks CRUD

Next Article

Is TikTok Shop Safe? What Buyers Should Know in 2026
← Back to the blog
geekskai Logo
geekskai

Public tools for developers and creators, plus optional Geekskai Audio Toolkit plans. Built with care.

Popular Tools

SoundCloud DownloaderSoundCloud to MP3SoundCloud to WAVSoundCloud PlaylistSoundCloud Artwork
View All Tools

Resources

BlogAbout MePricingTagsProjectsPrivacy PolicyTerms of ServiceRefund Policy

Connect With Us

mailMail
githubGitHub
twitterTwitter
linkedinLinkedin
© 2026 geekskai • All rights reserved

Vite runs and builds the React client. SWR manages a keyed client cache and revalidation. Neither automatically creates an /api route. The example below includes a local API so the read and mutation paths have a defined contract.

It uses React function components and the SWR 2 mutation API. Use a Node.js version supported by the current Vite guide and keep the generated lockfile to record the actual dependency versions.

Create a React project

npm create vite@latest my-swr-app -- --template react
cd my-swr-app
npm install
npm install swr express

The extra -- forwards the template option through npm. Keep the React plugin supplied by that template. There is no need to switch to the SWC plugin just to use SWR or add a manual optimizeDeps entry without a specific problem.

Add a local demonstration API

Create mock-api.mjs at the project root:

// mock-api.mjs
import express from "express"
import { randomUUID } from "node:crypto"

const API_HOST = "127.0.0.1"
const API_PORT = 4174
const TODOS_PATH = "/api/todos"
const TITLE_LIMIT = 80
const todos = []
const app = express()
app.use(express.json({ limit: "1kb" }))

app.get(TODOS_PATH, (_request, response) => {
  response.json(todos)
})

app.post(TODOS_PATH, (request, response) => {
  const title = request.body?.title
  if (typeof title !== "string" || !title.trim() || title.length > TITLE_LIMIT) {
    response.status(400).json({ message: "A title of 1 to 80 characters is required." })
    return
  }
  const savedTodo = { id: randomUUID(), title: title.trim() }
  todos.push(savedTodo)
  response.status(201).json(savedTodo)
})

app.listen(API_PORT, API_HOST, () => {
  console.log("Demo API listening on http://127.0.0.1:4174")
})

This Express fixture keeps synthetic todos in memory. GET /api/todos returns an array; POST /api/todos accepts a JSON title and returns the created record. Restarting it clears the records. It listens only on the loopback address and has no production authentication, persistence, or idempotency handling. Do not expose it as a production service.

Proxy client requests during development

For the React template using @vitejs/plugin-react, use this vite.config.js:

import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": "http://127.0.0.1:4174",
    },
  },
})

The development proxy forwards /api requests to the fixture. This setting does not deploy an API or configure a production reverse proxy. Keep the plugin already generated for a different template rather than copying an import for a package you have not installed.

Check HTTP status and response shape

Create src/todos-api.js:

// src/todos-api.js
export const TODOS_PATH = "/api/todos"

function isTodo(record) {
  return record !== null && typeof record === "object" &&
    typeof record.id === "string" && typeof record.title === "string"
}

export async function readTodos(url) {
  const response = await fetch(url)
  if (!response.ok) {
    throw new Error("List request failed: " + response.status)
  }
  const receivedTodos = await response.json()
  if (!Array.isArray(receivedTodos) || !receivedTodos.every(isTodo)) {
    throw new Error("Invalid todo list")
  }
  return receivedTodos
}

export async function createTodo(url, { arg: title }) {
  const response = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title }),
  })
  if (!response.ok) {
    throw new Error("Save request failed: " + response.status)
  }
  const savedTodo = await response.json()
  if (!isTodo(savedTodo)) {
    throw new Error("Invalid saved todo")
  }
  return savedTodo
}

fetch does not reject solely because the server returns an HTTP error status. The read function rejects non-success responses and invalid records so SWR can expose an error instead of presenting bad JSON as a valid list. The write function validates the returned record separately.

Keep the mutation and refresh explicit

Replace src/App.jsx with:

// src/App.jsx
import { useState } from "react"
import useSWR from "swr"
import useSWRMutation from "swr/mutation"
import { TODOS_PATH, readTodos, createTodo } from "./todos-api.js"

export function useTodos() {
  const query = useSWR(TODOS_PATH, readTodos, { shouldRetryOnError: false })
  const mutation = useSWRMutation(TODOS_PATH, createTodo, { revalidate: false })
  return {
    todos: query.data,
    loadError: query.error,
    isLoading: query.isLoading,
    isValidating: query.isValidating,
    refresh: query.mutate,
    addTodo: mutation.trigger,
    saveError: mutation.error,
    isSaving: mutation.isMutating,
  }
}

function TodoResults({ todos, isLoading, loadError }) {
  if (isLoading) {
    return <p role="status">Loading...</p>
  }
  if (!todos) {
    if (loadError) {
      return <p>No list is available.</p>
    }
    return <p role="status">Waiting for a list.</p>
  }
  if (todos.length === 0) {
    return <p>No todos yet.</p>
  }
  return <ul>{todos.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
}

export default function App() {
  const { todos, loadError, isLoading, isValidating, refresh,
    addTodo, saveError, isSaving } = useTodos()
  const [notice, setNotice] = useState("")

  async function handleRefresh() {
    try {
      await refresh()
    } catch (error) {
      console.error("Todo list refresh failed", error)
    }
  }

  async function handleSubmit(event) {
    event.preventDefault()
    const formElement = event.currentTarget
    const submittedFields = new FormData(formElement)
    const title = String(submittedFields.get("title") ?? "").trim()
    if (!title || isSaving) {
      return
    }
    setNotice("")
    try {
      await addTodo(title)
    } catch (error) {
      console.error("Todo save failed", error)
      return
    }
    formElement.reset()
    setNotice("Saved. The list may still be refreshing.")
    await handleRefresh()
  }

  return (
    <main>
      <h1>Todo demo</h1>
      {loadError && <p role="alert">List request failed. Retry to refresh it.</p>}
      <TodoResults todos={todos} isLoading={isLoading} loadError={loadError} />
      {isValidating && !isLoading && <p role="status">Refreshing...</p>}
      <button type="button" onClick={handleRefresh} disabled={isValidating}>Refresh list</button>
      <form onSubmit={handleSubmit}>
        <label>Title<input name="title" required maxLength={80} /></label>
        <button type="submit" disabled={isSaving}>Add todo</button>
      </form>
      {saveError && <p role="alert">Save could not be confirmed. Check the list before retrying.</p>}
      {notice && <p role="status">{notice}</p>}
    </main>
  )
}

Keep the template's existing entry point importing App. The useTodos hook owns request state; the component renders it and handles form events. The handler captures the form before awaiting because event.currentTarget is only meaningful during the event dispatch.

The example waits for the write and then asks the bound mutate function to refresh the list. It deliberately avoids an optimistic append: a rejected request never becomes an apparently saved record. A failed response after a server write can still make the outcome uncertain, so the message asks the user to check before retrying. Production writes need an appropriate idempotency strategy.

SWR's mutation documentation distinguishes bound/global mutate from useSWRMutation. The trigger returned by useSWRMutation starts its configured mutation; it is not the old generic name for “only revalidate.” A bound mutate with no replacement value requests revalidation of that hook's key.

Run and verify the complete path

Start the API in one terminal:

node mock-api.mjs

Start Vite in another:

npm run dev

Open the URL Vite prints. These are expected behaviors for the example, not claims about a test on your machine:

CheckExpected result
First successful GETNo todos yet
Add a non-empty titlePOST succeeds; a later GET shows the saved title
Submit whitespaceNo write request
Stop the API, then refreshVisible list error; previously loaded records may remain
Stop the API, then addSave error; no locally invented saved row
Restart the fixture and refreshEmpty list, because the fixture is not persistent

Inspect the browser Network panel for the GET and POST and distinguish the Vite page from the API request. A successful page load does not prove the backend route exists. Also test a malformed response and an HTTP error in a controlled test environment.

Understand cached data and failure together

SWR can retain previously loaded data while a revalidation fails. The UI therefore displays loadError alongside any existing list. Loading, refreshing, empty, and failed states have different meanings. See SWR error handling.

Automatic retries are disabled here to make failures and manual retries visible. Choose a retry policy for the real API, considering authorization failures, rate limits, and operations that must not repeat. Request deduplication does not make server data update in real time; polling or a subscription is a separate choice.

Extend the example deliberately

For conditional fetching, use a null key until the input or authorization state is ready. Do not put a secret in the key or assume a disabled client request protects the server. Authentication and authorization must be enforced by the backend.

For pagination, select the current SWR pagination API and define the server's cursor or page contract. For server rendering, use the framework's supported data and hydration path; a plain Vite React starter is not an SSR application merely because it uses SWR.

Before deployment, replace the fixture with an authorized persistent API, configure the production request path, validate records at the boundary, and test unsuccessful writes and revalidation. Keep the simpler pessimistic update until an optimistic experience has a defined rollback and race-handling strategy.