{"id":15099,"library":"dexie-react-hooks","title":"React Hooks for Dexie.js","description":"dexie-react-hooks provides a collection of React hooks designed for seamlessly integrating Dexie.js, a wrapper for IndexedDB, into React applications. It facilitates reactive data fetching and real-time updates directly from the IndexedDB database, abstracting away the complexities of manual subscription management. The current stable version is 4.4.0, aligning with the broader Dexie.js ecosystem releases. The package follows a release cadence tied closely to the main Dexie.js library, with frequent updates addressing bug fixes and new features, such as enhanced Y.js integration and Dexie Cloud capabilities. Its key differentiators include simplifying reactive state management with IndexedDB, offering idiomatic React patterns for database interactions, and ensuring components re-render automatically when underlying data changes.","status":"active","version":"4.4.0","language":"javascript","source_language":"en","source_url":"https://github.com/dexie/Dexie.js","tags":["javascript","react","hooks","indexeddb","storage","data-fetching","reactive","subscription","dexie","typescript"],"install":[{"cmd":"npm install dexie-react-hooks","lang":"bash","label":"npm"},{"cmd":"yarn add dexie-react-hooks","lang":"bash","label":"yarn"},{"cmd":"pnpm add dexie-react-hooks","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core IndexedDB abstraction layer; this package provides React bindings for it.","package":"dexie","optional":false},{"reason":"React framework for component integration and hook functionality.","package":"react","optional":false}],"imports":[{"note":"Primary hook for reactive data fetching. Use named import in ESM environments.","wrong":"const useLiveQuery = require('dexie-react-hooks').useLiveQuery","symbol":"useLiveQuery","correct":"import { useLiveQuery } from 'dexie-react-hooks'"},{"note":"Hook to access the Dexie database instance, typically used with a DexieProvider context.","wrong":"import Dexie from 'dexie-react-hooks'; // Incorrectly assuming a default export for the instance","symbol":"useDexie","correct":"import { useDexie } from 'dexie-react-hooks'"},{"note":"Hook introduced in v4.2.0 for Y.js integration, typically used in conjunction with dexie-cloud-addon and y-dexie.","symbol":"useDocument","correct":"import { useDocument } from 'dexie-react-hooks'"}],"quickstart":{"code":"import React from 'react';\nimport { useLiveQuery } from 'dexie-react-hooks';\nimport Dexie from 'dexie';\n\n// Define your Dexie database schema and class\ninterface Todo {\n  id?: number;\n  title: string;\n  completed: boolean;\n}\n\nclass MyDatabase extends Dexie {\n  todos!: Dexie.Table<Todo, number>;\n\n  constructor() {\n    super('MyTodoDatabase');\n    this.version(1).stores({\n      todos: '++id, title, completed'\n    });\n  }\n}\n\n// Instantiate the database\nconst db = new MyDatabase();\n\n// React component using the useLiveQuery hook\nconst TodoList: React.FC = () => {\n  // useLiveQuery subscribes to changes in db.todos\n  const todos = useLiveQuery(\n    () => db.todos.toArray(),\n    [] // Empty dependency array means the query function is stable; re-queries on DB changes.\n  );\n\n  const addTodo = async () => {\n    await db.todos.add({ title: `New Todo ${Date.now()}`, completed: false });\n  };\n\n  const toggleTodo = async (id: number) => {\n    const todo = await db.todos.get(id);\n    if (todo) {\n      await db.todos.update(id, { completed: !todo.completed });\n    }\n  };\n\n  if (!todos) return <div>Loading todos...</div>; // Data is null on first render until query resolves\n\n  return (\n    <div>\n      <h1>My Todos</h1>\n      <button onClick={addTodo}>Add Todo</button>\n      <ul>\n        {todos.map(todo => (\n          <li key={todo.id}>\n            <input\n              type=\"checkbox\"\n              checked={todo.completed}\n              onChange={() => toggleTodo(todo.id!)}\n            />\n            <span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>\n              {todo.title}\n            </span>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n};\n\nexport default TodoList;","lang":"typescript","description":"Demonstrates how to define a Dexie database, create a React component, and use `useLiveQuery` to fetch and display data reactively, with add and toggle functionality."},"warnings":[{"fix":"For Y.js integration, ensure `npm install y-dexie` and update `DexieYProvider` imports from `y-dexie` instead of `dexie`.","message":"Dexie.js v4.2.0-rc.1 and later introduced a significant change for Y.js users, moving `DexieYProvider` from the `dexie` package into a new `y-dexie` package. While `dexie-react-hooks`'s `useDocument` is related, users integrating Y.js must ensure both `dexie` and `y-dexie` dependencies are correctly installed and imported as per `dexie@4.2.0` and above.","severity":"breaking","affected_versions":">=4.2.0"},{"fix":"Always check your `dexie` and `react` versions and ensure they fall within the specified peer dependency ranges. Use `npm install` or `yarn install` to resolve peer dependencies automatically if your package manager supports it, or manually install compatible versions.","message":"This package has a peer dependency on `dexie` version `>=4.2.0-alpha.1 <5.0.0` and `react` version `>=16`. Using incompatible versions of `dexie` or `react` can lead to runtime errors, unexpected behavior, or broken reactivity due to API mismatches or internal inconsistencies.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Always use Dexie's API methods for all database modifications. If you need to interact with IndexedDB directly, consider manually triggering a re-render or explicitly notifying `useLiveQuery` if possible.","message":"`useLiveQuery` relies on Dexie's internal change tracking for reactivity. For optimal performance and correct re-renders, ensure that all database operations (add, put, delete, update) are performed exclusively through the Dexie instance (e.g., `db.table.method()`). Direct mutations via IndexedDB APIs will not trigger `useLiveQuery` updates.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Review the variables used inside your `useLiveQuery` callback function. If any props or state variables are used, include them in the dependency array to ensure the query re-runs when those values change.","message":"The dependency array for `useLiveQuery` (the second argument) should accurately reflect all external values that, if changed, would require re-executing the query function. An empty array `[]` means the query runs once and then re-subscribes only on database changes; if the query itself depends on component props or state, these must be included in the array to ensure correct reactivity.","severity":"gotcha","affected_versions":">=4.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure the package is installed with `npm install dexie-react-hooks dexie react react-dom`. Use `import { useLiveQuery } from 'dexie-react-hooks'` in an ESM-compatible environment, or configure your build system for CJS compatibility.","cause":"The package is not installed, there's a wrong import path, or a CommonJS/ESM module mismatch.","error":"Error: Cannot find module 'dexie-react-hooks' or TypeError: Cannot read properties of undefined (reading 'useLiveQuery')"},{"fix":"Ensure all database modifications (add, put, delete, update) are done via Dexie's API. Check that your `dexie` package version is `>=4.0.9`. Verify the `useLiveQuery` dependency array includes all external variables used within the query function.","cause":"The underlying Dexie operations are not correctly triggering reactivity, the query's dependency array is incorrect, or an outdated Dexie.js version is in use.","error":"useLiveQuery does not update when data changes"},{"fix":"Review your Dexie database schema definition, ensuring tables are correctly defined in `db.version().stores({})` and that the `db` instance is correctly created. For TypeScript, ensure proper typing for your database and its tables.","cause":"The Dexie database instance or a specific table is not properly initialized, typed, or the database class is not correctly extending `Dexie`.","error":"TypeError: db.table.method is not a function (e.g. db.todos.toArray is not a function)"}],"ecosystem":"npm"}