React hook for
IndexedDBthat mimicsuseStateAPI
npm install use-dbWhy this over use-local-storage-state?
- Capacity.
IndexedDBcan store hundred of megabytes to gigabytes of data.localStoragelimit is around 5-10MB. - Performance.
IndexedDBis async and doesn't block the UI.IndexedDBcan store objects without serialization which shaves off the time to doJSON.parse()andJSON.stringify()that's needed when working withlocalStorage. - Availability.
IndexedDBis available both in Web Worker and Service Worker,localStorageis not. You can write data in those places and then access it in the main thread. - Maintenance. I've been consistently maintaining many open-source libraries including
use-local-storage-statewith ~500k downloaders per month.
import useDb from 'use-db'
export default function Todos() {
const [todos, setTodos] = useDb('todos', {
defaultValue: ['buy avocado', 'do 50 push-ups']
})
}Todo list example
import React, { useState } from 'react'
import useDb from 'use-db'
export default function Todos() {
const [todos, setTodos] = useDb('todos', {
defaultValue: ['buy avocado']
})
const [query, setQuery] = useState('')
function onClick() {
setQuery('')
setTodos([...todos, query])
}
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<button onClick={onClick}>Create</button>
{todos.map(todo => (
<div>{todo}</div>
))}
</>
)
}Removing the data from IndexedDB and resetting to the default
The removeItem() method will reset the value to its default and will remove the data from the IndexedDB. It returns to the same state as when the hook was initially created.
import useDb from 'use-db'
export default function Todos() {
const [todos, setTodos, removeItem] = useDb('todos', {
defaultValue: ['buy avocado']
})
function onClick() {
removeItem()
}
}Returns [value, setValue, removeItem] when called. The first two values are the same as useState(). The third value calls IDBObjectStore.delete() and removes the data from the db.
Type: string
IndexedDB that was created from another place in the codebase or in an old version of the application.
Type: any
Default: undefined
The default value. You can think of it as the same as useState(defaultValue).
Type: boolean
Default: true
IndexedDB is async. When optimistic is enabled, calling setState will synchronously/immediately update the state and it will roll back the state if adding the data to the database fails. You can disable by setting optimistic: false.
use-storage-state— SupportslocalStorage,sessionStorage, and any otherStoragecompatible API.use-local-storage-state— Similar to this hook but forlocalStorage.use-session-storage-state— Similar to this hook but forsessionStorage.local-db-storage— Tiny wrapper aroundIndexedDBthat mimicslocalStorageAPI.