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.0.2

Published

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

Downloads

136

Readme

useDbState

useDbState is a custom React hook that allows you to persist state in IndexedDB. It provides an easy-to-use Hook similar to useState, but with the added benefit of persistent storage. It uses IndexedDB to store and retrieve state, ensuring that it is always available even after the user closes the browser tab or device.

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

Installation

npm install use-db-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>
  );
}

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

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>
  );
}

export default ComponentTwo;

In this example, useDbState is used to create a state variable myValue with a setter setMyValue. The initial value of myValue is an empty string. 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 the component unmounts.

when useDbState is used with the same key myValue in another component, it will be able to access the same state value.

API

useDbState

Parameters

  • key (string): The key under which the value is stored in IndexedDB.
  • defaultValue (any): The default value if no value is found in IndexedDB.
  • dbName (string, optional): The name of the IndexedDB database. Defaults to 'userDatabase'.
  • storeName (string, optional): The name of the IndexedDB object store. Defaults to 'userData'.

useDbState returns an array with two elements:

  • The current state value.
  • A setter function to update the state. This function has the same API as the setter returned by useState.

useDbKeyRemover

useDbKeyRemover takes two arguments:

  • dbName (optional): The name of the IndexedDB database. If not provided, defaults to 'userDatabase'.

  • storeName (optional): The name of the object store within the database. If not provided, defaults to 'userData'.

useDbKeyRemover returns a function that removes the given key from the IndexedDB object store.

  • key (required): The key to remove from the IndexedDB object store using the returned function.
import { useDbState, useDbKeyRemover } from 'use-db-state';

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

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

export default App;

In this example, useDbState is used to create a state variable myValue with a setter setMyValue. The initial value of myValue is an empty string. The state is persisted in a custom IndexedDB database named 'myCustomDatabase', and within that database, it’s stored in an object store named 'myCustomStore'. The state will be preserved across page reloads.

When to Use

Use useDbState when you need to persist state across page reloads. It’s particularly useful for things like user preferences or form data that you want to preserve if the user accidentally refreshes or navigates away from the page.

Advantages of using IndexedDB

useDbState uses IndexedDB for data persistence, which has several advantages over localStorage:

  1. Larger Storage Capacity: IndexedDB can store large amounts of data, ranging from a few megabytes to gigabytes. In contrast, localStorage usually has a storage limit of around 5-10MB per domain.
  2. Complex Data Queries: IndexedDB supports advanced queries using indexes. localStorage, on the other hand, only supports key-value pairs and does not have built-in support for indexing or complex queries
  3. Asynchronous Operations: IndexedDB operations are asynchronous, preventing blocking of the main thread.
  4. Structured Data: IndexedDB can store complex structured data like objects and arrays. localStorage only supports strings.
  5. Durability: Data in IndexedDB persists even when the browser is closed, or the system crashes.
  6. Scalability: IndexedDB scales well with large datasets.

These advantages make useDbState a powerful tool for managing state in your React applications.

Limitations

useDbState uses IndexedDB for storage, which is asynchronous and has certain limitations. It’s not suitable for storing very large amounts of data in a single state variable, and complex data structures like Map or Set may need to be serialized before storage.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on the GitHub repository.

License

This project is licensed under the MIT license