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

@custom-react-hooks/use-storage

v1.5.1

Published

`useStorage` is a versatile hook for interacting with Web Storage (localStorage and sessionStorage) in React applications. It simplifies storage operations and ensures compatibility with server-side rendering.

Downloads

779

Readme

useStorage Hook

useStorage is a versatile hook for interacting with Web Storage (localStorage and sessionStorage) in React applications. It simplifies storage operations and ensures compatibility with server-side rendering.

Features

  • LocalStorage and SessionStorage: Works with both localStorage and sessionStorage.
  • Server-Side Rendering Support: Safely handles server-side rendering scenarios.
  • Automatic JSON Handling: Automatically serializes and deserializes stored values.
  • Synchronized State: Keeps the React state in sync with storage changes.
  • Error Handling: Provides error handling for storage access and manipulation.

Installation

Installing Only Current Hooks

npm install @custom-react-hooks/use-storage

or

yarn add @custom-react-hooks/use-storage

Installing All Hooks

npm install @custom-react-hooks/all

or

yarn add @custom-react-hooks/all

Importing the Hook

The useStorage hook must be imported using a named import as shown below:

Named Import:

import { useStorage } from '@custom-react-hooks/use-storage';

This approach ensures that the hook integrates seamlessly into your project, maintaining consistency and predictability in how you use our package.

Usage

import React from 'react';
import { useStorage } from '@custom-react-hooks/all';

const StorageList = ({ storageType }: { storageType: 'local' | 'session' }) => {
  const [items, setItems] = useStorage(`${storageType}-items`, [], storageType);

  const addItem = (item) => {
    setItems((prevItems) => [...prevItems, item]);
  };

  const removeItem = (index) => {
    setItems((prevItems) => prevItems.filter((_, i) => i !== index));
  };

  return (
    <div>
      <input
        type="text"
        onKeyDown={(e) => {
          if (e.key === 'Enter' && e.currentTarget.value) {
            addItem(e.currentTarget.value);
            e.currentTarget.value = '';
          }
        }}
        placeholder={`Add to ${storageType} storage`}
      />
      <h2>{storageType === 'local' ? 'LocalStorage' : 'SessionStorage'} List</h2>
      <ol>
        {items.map((item, index) => (
          <li key={index}>
            {item} <XCircleIcon onClick={() => removeItem(index)} />
          </li>
        ))}
      </ol>
    </div>
  );
};

const StorageComponent = () => (
  <div className="storage">
    <StorageList storageType="local" />
    <StorageList storageType="session" />
  </div>
);

return default StorageComponent;

In this example, the hook manages a value in localStorage, providing functions to read and update it.

API Reference

Parameters

  • key: The key under which to store the value in storage.
  • defaultValue: The default value to use if no item is found in storage.
  • storageType: Type of storage to use ('local' for localStorage, 'session' for sessionStorage).

Returns

  • Returns an array with the stored value and a setter function to update it.

Use Cases

  • State Persistence: Persist state between page reloads, such as user preferences or session data.
  • Form Data Saving: Save form data in the browser to prevent loss on page refresh.
  • Local Data Caching: Cache data locally to reduce API calls and improve loading times.
  • Feature Toggling: Store feature flags or toggles in the browser for conditional feature rendering.

Contributing

Contributions to enhance useStorage are welcome. Feel free to submit issues or pull requests to the repository.