geekskai Logogeekskai
ToolsBlogPricing
Sign in
Sign in
ToolsBlogSign in
Saturday, February 1, 2025|8min read

Expo SQLite and TanStack Query v5: Local Tasks CRUD

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

Tags

reactreact-nativeexposqlitereact-query

Previous Article

What is M&E Engineer: Complete Guide to Mechanical and Electrical Engineering in 2025

Next Article

Mastering React SWR Vite Integration
← 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
Expo SQLite with TanStack Query

Use SQLite as the durable local store and TanStack Query as the in-memory query and mutation coordinator. A Query cache is not a database, and adding useMutation does not create a background synchronization service.

This example is a local-only task list for Android or iOS. It covers create, read, completion updates, and deletion; it does not use TypeORM or write to a remote backend. The UI shows loading, empty, read-error, initialization-error, and mutation-error states.

Version scope and setup

The example targets this fixed, metadata-compatible combination, rather than mixing the legacy transaction API with Query v5:

PackageVersion
expo58.0.23
react19.3.0
react-native0.88.1
expo-sqlite58.0.15
@tanstack/react-query5.107.1

Expo SDK 58 requires Node 22.13.x or newer. In an SDK 58 blank JavaScript project that uses App.jsx as its entry component, install these exact package versions and retain the resulting lockfile. Use the project's Expo CLI; do not install the retired global expo-cli. If your project uses Expo Router, put the providers in its root layout instead of assuming that a new App.jsx will replace its entry point.

npm install --save-exact [email protected] [email protected] [email protected] [email protected] @tanstack/[email protected]
npx expo install --check

This version table establishes the intended dependency boundary, not a native-device test result. If you choose a different SDK, use that SDK's compatibility guidance and revalidate the example. The older openDatabase/transaction/executeSql callback examples cannot be awaited as if they were this Promise API.

1. Create the database operations

Save tasks.js. SQLiteProvider will call initializeDatabase before rendering its children. The database name used below is dedicated to this demo. CREATE TABLE IF NOT EXISTS initializes a fresh schema; it does not migrate an older table when its columns change.

export const TASK_QUERY_KEY = ["local-tasks"]
export const CREATE_TASKS_SQL = "CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL CHECK(length(trim(title)) > 0), isCompleted INTEGER NOT NULL DEFAULT 0 CHECK(isCompleted IN (0, 1)));"

export async function initializeDatabase(database) {
  // Static schema only. Bind user input in runAsync instead of interpolating SQL.
  await database.execAsync(CREATE_TASKS_SQL)
}

export async function fetchTasks(database) {
  return database.getAllAsync("SELECT id, title, isCompleted FROM tasks ORDER BY id")
}

export function taskQueryOptions(database) {
  return {
    queryKey: TASK_QUERY_KEY,
    queryFn: () => fetchTasks(database),
    networkMode: "always",
    staleTime: 0,
  }
}

export async function createTask({ database, title }) {
  if (typeof title !== "string" || title.trim() === "") {
    throw new Error("Enter a task title")
  }
  const taskTitle = title.trim()
  return database.runAsync("INSERT INTO tasks (title, isCompleted) VALUES (?, 0)", taskTitle)
}

function requireTaskId(id) {
  if (!Number.isSafeInteger(id) || id <= 0) {
    throw new TypeError("Task ID must be a positive safe integer")
  }
}

export async function setTaskCompleted({ database, id, isCompleted }) {
  requireTaskId(id)
  if (typeof isCompleted !== "boolean") {
    throw new TypeError("isCompleted must be boolean")
  }
  const completionValue = isCompleted ? 1 : 0
  return database.runAsync("UPDATE tasks SET isCompleted = ? WHERE id = ?", completionValue, id)
}

export async function deleteTask({ database, id }) {
  requireTaskId(id)
  return database.runAsync("DELETE FROM tasks WHERE id = ?", id)
}

All titles and IDs are passed as bound values. execAsync is reserved for the static schema, not user input. SQLite stores the completion state as 0 or 1. The primary key comes from SQLite; a title containing an apostrophe must remain text, not become SQL.

2. Connect queries and mutations

Save useTasks.js. Query v5 takes an options object. Each local operation sets networkMode to always because it does not depend on internet access. After a write resolves, onSuccess returns the invalidation promise so an active task query can read the committed rows again.

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { useSQLiteContext } from "expo-sqlite"
import { TASK_QUERY_KEY, taskQueryOptions, createTask, setTaskCompleted, deleteTask } from "./tasks"

export function useTasks() {
  const database = useSQLiteContext()
  const queryClient = useQueryClient()
  const taskQuery = useQuery(taskQueryOptions(database))
  const refreshTasks = () => queryClient.invalidateQueries({ queryKey: TASK_QUERY_KEY })
  const createTaskMutation = useMutation({
    mutationFn: title => createTask({ database, title }),
    networkMode: "always", onSuccess: refreshTasks,
  })
  const completeTaskMutation = useMutation({
    mutationFn: task => setTaskCompleted({ database, id: task.id, isCompleted: !Boolean(task.isCompleted) }),
    networkMode: "always", onSuccess: refreshTasks,
  })
  const deleteTaskMutation = useMutation({
    mutationFn: id => deleteTask({ database, id }),
    networkMode: "always", onSuccess: refreshTasks,
  })
  return { taskQuery, createTaskMutation, completeTaskMutation, deleteTaskMutation }
}

The single query key belongs to this one demo database. A multi-account or multi-database app must isolate both its cache keys and database ownership. Query invalidation refreshes observed queries; it does not turn arbitrary writes elsewhere in the app into a live SQLite subscription.

3. Render the task list and controls

Save TaskScreen.jsx. Disable overlapping writes while a mutation is pending. A failed write remains an error instead of being presented as an empty list. Changing completion status and deleting a task both use the same read-after-write refresh path.

import { useState } from "react"
import { Button, ScrollView, Text, TextInput, View } from "react-native"
import { useTasks } from "./useTasks"

export default function TaskScreen() {
  const [title, setTitle] = useState("")
  const { taskQuery, createTaskMutation, completeTaskMutation, deleteTaskMutation } = useTasks()
  const isBusy = createTaskMutation.isPending || completeTaskMutation.isPending || deleteTaskMutation.isPending
  const mutationError = createTaskMutation.error || completeTaskMutation.error || deleteTaskMutation.error
  if (taskQuery.isPending) {
    return <Text>Loading local tasks...</Text>
  }
  if (taskQuery.isError) {
    return <View><Text accessibilityRole="alert">{taskQuery.error.message}</Text><Button title="Retry read" onPress={() => taskQuery.refetch()} /></View>
  }
  return (
    <ScrollView contentInsetAdjustmentBehavior="automatic">
      <TextInput accessibilityLabel="Task title" value={title} onChangeText={setTitle} editable={!isBusy} />
      <Button title="Add task" disabled={isBusy || title.trim() === ""}
        onPress={() => createTaskMutation.mutate(title, { onSuccess: () => setTitle("") })} />
      {mutationError && <Text accessibilityRole="alert">{mutationError.message}</Text>}
      {taskQuery.data.length === 0 && <Text>No local tasks yet.</Text>}
      {taskQuery.data.map(task => (
        <View key={task.id}>
          <Text>{task.title}</Text>
          <Button title={task.isCompleted ? "Mark incomplete" : "Mark complete"} disabled={isBusy}
            onPress={() => completeTaskMutation.mutate(task)} />
          <Button title="Delete task" disabled={isBusy} onPress={() => deleteTaskMutation.mutate(task.id)} />
        </View>
      ))}
    </ScrollView>
  )
}

Save App.jsx. Keep one stable QueryClient for this application. An initialization failure is logged and displayed instead of leaving a permanently blank screen.

import { useState } from "react"
import { Text } from "react-native"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { SQLiteProvider } from "expo-sqlite"
import { initializeDatabase } from "./tasks"
import TaskScreen from "./TaskScreen"

const queryClient = new QueryClient()

export default function App() {
  const [databaseError, setDatabaseError] = useState(null)
  function handleDatabaseError(error) {
    console.error("Local task database initialization failed:", error)
    setDatabaseError(error)
  }
  if (databaseError) {
    return <Text accessibilityRole="alert">Database unavailable: {databaseError.message}</Text>
  }
  return (
    <QueryClientProvider client={queryClient}>
      <SQLiteProvider databaseName="task-demo-v1.db" onInit={initializeDatabase} onError={handleDatabaseError}>
        <TaskScreen />
      </SQLiteProvider>
    </QueryClientProvider>
  )
}

4. Check the local loop on a device

Start the intended Android or iOS development build. Confirm these outcomes before shipping:

Input or actionExpected result
First launch of the demo databaseAn empty task list rather than a missing-table error
Add a task containing a comma, Chinese text, or an apostropheOne row with the original title; the list refreshes
Enter only spacesThe add control is disabled; createTask also rejects a blank title
Mark complete, then incompleteThe same row changes between 1 and 0 after each write
Delete one taskThat row disappears; other rows remain
Disable network connectivityLocal reads and writes still run; they do not wait for a remote connection
Close and reopen the appSQLite rows remain and a new QueryClient reads them again
Force an invalid SQL operation in a disposable test buildA visible error; no claim that the write succeeded

Node SQLite and QueryCore checks can exercise the SQL, parameter binding, and query invalidation with offline network state. They do not validate Expo's native bridge, Provider lifecycle, device storage, or Android/iOS builds. Native acceptance and restart checks are still required for the chosen project and device. Web SQLite has additional platform setup and is outside this mobile example.

Cache lifetime and synchronization boundaries

In Query v5, gcTime replaces cacheTime; it controls when an unused query can be garbage-collected. Neither gcTime nor staleTime persists SQLite rows or saves a remote mutation queue. The example reads the durable database again after the process restarts.

Remote synchronization needs an explicit outbox or persisted mutation strategy, retry limits, idempotent server operations, and conflict handling. Query can coordinate such work, but the code above implements none of those guarantees. React Native foreground refetching also needs the documented AppState/focusManager integration when the product requires it; browser window-focus behavior is not a substitute.

Official references

  • Expo SDK 58 release
  • Expo 58.0.23 compatibility matrix
  • Expo SQLite initialization, parameter binding, and Provider APIs
  • TanStack Query v5 migration
  • Query network modes
  • Invalidation after mutations
  • Mutation persistence limitations
  • React Native focus integration