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-local-storage-safe

v0.2.6

Published

React hook for using LocalStorage safely

Downloads

19

Readme

use-local-storage-safe

React hook for using LocalStorage safely

License Downloads size build badge-branches badge-functions badge-lines badge-statements

Installation

npm i use-local-storage-safe        # npm
yarn add use-local-storage-safe     # yarn
pnpm i use-local-storage-safe       # pnpm

Why

  • Persist data to local storage using a React useState-like interface.
  • Validates stored content on hook initialization to prevent collisions and handle legacy data
  • Fit any hooks-compatible version of React >=16.8.0
  • ESM - ECMAScript modules; CJS - CommonJS support
  • Cross-Browser State Synchronization options.sync?: boolean
  • SSR support (NextJS, Astro, Remix)

Usage

Basic

import { useLocalStorageSafe } from 'use-local-storage-safe'

export default function NameComponent() {
    const [userName, setUserName] = useLocalStorageSafe('name-storage-key', 'default-name')
}

Advanced

import { useLocalStorageSafe } from 'use-local-storage-safe'
// data could be validated with plain JS or any other library
import { z } from "zod";

const User = z.object({
    firstName: z.string().min(1).max(18),
    lastName: z.string().min(1).max(18),
    email: z.string().email(),
});

type User = z.infer<typeof User>

export default function UserComponent() {
    const [user, setUser] = useLocalStorageSafe<User>(
        "user-storage-key",
        {
            firstName: "example name",
            lastName: "example last name",
            email: "[email protected]",
        },
        // validate stored data on hook initialization
        { validateInit: (user) => User.safeParse(user).success }
    );

    return (
        <div>
            <p>First Name: {user.firstName}</p>
            <p>Last Name: {user.lastName}</p>
            <p>Email: {user.email}</p>

            <button
                onClick={() =>
                    setUser({ firstName: "U", lastName: "Nu", email: "[email protected]" })
                }
            >
                Set User
            </button>
        </div>
    );
}

API

function useLocalStorageSafe<T>(key: string, defaultValue?: T, options?: Options<T>): [T, Dispatch<SetStateAction<T>>];

interface Options<T> {
    stringify?: (value: unknown) => string;
    parse?: (string: string) => string;
    log?: (message: unknown) => void;
    validateInit?: (value: T) => boolean;
    sync?: boolean;
    silent?: boolean;
}
  • key - The key under which the state value will be stored in the local storage.
  • defaultValue - The initial value for the state. If the key does not exist in the local storage, this value will be used as the default.
  • options - An object containing additional customization options for the hook.
    • options?.stringify - A function that converts the state value to a string before storing it in the local storage. JSON.stringify by default.
    • options?.parse - A function that converts the string value from the local storage back into its original form. JSON.parse by default.
    • options?.log - A function that receives a message as an argument and logs it. This can be used for debugging or logging purposes. console.log by default.
    • options?.validateInit - A function that validates stored value during hook initialization. If the validation returns false, invalid value will be removed and replaced by default if provided.
    • options?.sync - A boolean indicating whether the state should be synchronized across multiple tabs, windows and iframes. true by default.
    • options?.silent - A boolean indicating whether the hook should suppress an error occurs while accessing the local storage. true by default.