npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-db-state

v2.1.1

Published

A React Hook that uses IndexedDB in the browser to persistently store and retrieve state.

Downloads

139

Readme

useDbState

npm version npm downloads license

🚀 A powerful React hook for persistent state management with IndexedDB, featuring global state management, automatic caching, and optimized performance.

useDbState is a production-ready React hook that combines the simplicity of useState with the persistence of IndexedDB and power of global state management. It's perfect for managing application-wide state, offline-first applications, and sharing state between components.

[email protected] can now be used as a global state!

✨ Features

  • 🌍 Global State Management: Share state seamlessly between components
  • 💾 Persistent Storage: Data persists through page reloads and browser restarts
  • Performance Optimized:
    • In-memory caching for fast reads
    • Debounced writes to reduce database operations
    • Queued operations to prevent race conditions
  • 🛡️ Reliable: Automatic error handling and recovery
  • 🔍 Developer Friendly: Comprehensive debugging support
  • 📱 Universal: Works in all modern browsers and React Native

🎮 Live Examples

Here are several live examples demonstrating different use cases and features of useDbState:

Basic Counter with Persistence

View Demo A simple counter example showing how state persists across page refreshes. Perfect for getting started with useDbState.

String State Sharing

View Demo Demonstrates how two components can share a string state, showing real-time updates between components.

Optimized Number Updates

View Demo Showcases the hook's handling of rapid state changes with numbers, featuring:

  • Race condition prevention
  • Internal debouncing
  • Optimized performance for fast updates

Array State Management

View Demo Shows how arrays are handled in shared state:

  • Adding elements to array
  • Real-time updates across components
  • Array manipulation with persistence

Object State Handling

View Demo Demonstrates working with complex object states:

  • Object property updates
  • Nested object handling
  • State synchronization between components

Image Storage and Sharing

View Demo Advanced example showing:

  • Binary data storage
  • Image handling in IndexedDB
  • Sharing images between components
  • Efficient large data management

Each example is fully interactive and can be edited live on StackBlitz. They serve as both documentation and a playground for learning how to use useDbState effectively.

📦 Installation

npm install use-db-state
# or
yarn add use-db-state
# or
pnpm add use-db-state

🚀 Quick Start

import { useDbState } from 'use-db-state';

function Counter() {
  const [count, setCount] = useDbState('counter', 0);
  
  return (
    <button onClick={() => setCount(prev => prev + 1)}>
      Count: {count}
    </button>
  );
}

📖 Global State Usage

import { useDbState, useDbKeyRemover } from 'use-db-state';

function ComponentOne() {
  const [myValue, setMyValue] = useDbState('myValue', '');
  const removeMyKey = useDbKeyRemover(); 

  const handleChange = (e) => {
    setMyValue(e.target.value);
  };

  return (
    <div className="App">
      <h1>My App</h1>
      <div>
        <input type='text' value={myValue} onChange={handleChange} />
        <button onClick={() => removeMyKey('myValue')}>Remove myValue</button>
      </div>
    </div>
  );
}

function ComponentTwo() {
  const [myValue, setMyValue] = useDbState('myValue'); // You now have access to the myValue state from ComponentOne

  return (
    <div className="App">
      <h1>My App</h1>
      <div>
        <p>myValue: {myValue}</p>
      </div>
    </div>
  );
}

In this example, useDbState is used to create a global state variable myValue that can be accessed and modified from any component. The state is persisted in IndexedDB, so it will be preserved across page reloads. The useDbKeyRemover hook is used to remove the key myValue from the IndexedDB object store when needed.

📚 API Reference

useDbState

function useDbState<T>(
  key: string,
  defaultValue?: T,
  dbName?: string,
  storeName?: string,
  options?: {
    debounceTime?: number;
  }
): [T, (value: T | ((prev: T) => T)) => void]

Parameters

  • key (required): Unique identifier for the state
  • defaultValue: Initial value if none exists in storage
  • dbName: Database name (default: 'userDatabase')
  • storeName: Store name (default: 'userData')
  • options: Configuration object
    • debounceTime: Milliseconds to debounce writes (default: 100)

Returns

Returns a tuple containing:

  1. Current state value
  2. Setter function (accepts new value or updater function)

useDbKeyRemover

function useDbKeyRemover(
  dbName?: string,
  storeName?: string
): (key: string) => Promise<void>

⚡ Performance Considerations

  • In-Memory Cache: First reads are cached for instant access
  • Debounced Writes: Prevents excessive database operations
  • Operation Queue: Ensures write operations are atomic
  • Cleanup: Automatic subscription cleanup on unmount

🤝 Contributing

Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.

📄 License

MIT © Ajey Nagarkatti

🔍 Keywords

react, hook, indexeddb, state management, persistent storage, cross-tab synchronization, react-hooks, browser storage, offline-first, web storage, react state, database, web development, frontend, javascript