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

@kizz-js/use-local-storage

v1.0.3

Published

A Plain dependency free Js based but react hook like store for working with browser local storage in both vanilla js projects and react applications, with no react useEffect or page re-hydration needed!

Downloads

31

Readme

_useLocalStorage 🪣

Demo Screenshot

A Plain dependency free Js based utility or react hook like store, for working with browser local storage in both vanilla js projects and react applications, with no react useEffect or page re-hydration needed!

🔥 Features

  • Can work in react (Not server components!) without using useEffect.
  • Can cache and reset states definitely or for a given time per state basis!
  • Each state in local storage is uniquely separated, making it easy to work with!
  • Has methods to get, set and reset locally persisted state!
  • Has onChange method to listen and react to local state changes useful for synchronizing state in multiple tabs simultaneously!
  • Has no dependencies and supports both react and vanilla js projects

▶️ Installation


npm i @kizz-js/use-local-storage

For vanilla js projects a cdn is recommended, otherwise you have to refrence the file exactly after installation for example:


import { _useStorage } from './node_modules/@kizz-js/use-local-storage/dist/useLocalStorage.js';

while for others it's the usual stuff, just import from @kizz-js/use-local-storage and the rest will be just fine!

😇 Now, How It Works With An Example:

Import and instantiate the local storage utility as storage with optional options. Which can be storageType of storageType local or session but local storage by default. see MDN Docs docs for differences between session and local storage options.

For Example:


import { _useStorage } from '@kizz-js/use-local-storage';

// Use Local Storage & use local storage (used by default)
const storage = _useStorage();

// use session storage istead
const storage = _useStorage({storageType: "session"});

Set Data in Storage


const key = 'my-state';
const dataToStore = { username: 'kizz', id: 123 };

// Set data with caching options
storage.setState(key, dataToStore, {
  cacheTimeout: true, // false disables the cache
  cacheTime: 1000, // 60,000 milliseconds default
});

// just set data without any options
// storage.setState(key, dataToStore);

Retrieve Data from Storage


const retrievedData = storage.getState('my-state');
console.log('Retrieved data:', retrievedData);

Reset/Clear Storage

This will clear all local storage or storages, removing any previously set data, even if set through other ways other than _useLocalStorage!

So use intentionally, To reset or clear the local storage:

storage.resetStorage();

Listen To Storage Change Events

You can listen to storage change events using the onChange method and run any side effects or callbacks you would want to run whenever local state changes, say redirect a user to login when they logout etc. This is experimental and stil being tested, so use with caution!


storage.onChange((event) => {
  console.log('Storage changed:', event);
  // do something about the change... if you want to!
});

Here is an example of how most of those concepts come together

This is snippet from example directory, you can check it out for the html part, but as far as js is concerned, here we go:


'use strict';

import { _useStorage } from '@kizz-js/use-local-storage';

const form = document.querySelector('#loginForm');
const userNameInput = form.querySelector('#userNameInput');
const passwordInput = form.querySelector('#passwordInput');

const storage = _useStorage();

let stateKey = 'userLoginData';

form.addEventListener('submit', (e) => {
  e.preventDefault();

  let userName = userNameInput.value;
  let password = passwordInput.value;

  // set data in storage
  storage.setState(stateKey, { userName, password });
});

// retrive user data on page load
window.onload = () => {
  let user = storage.getState(stateKey);

  if (user) {
    console.log('Hello, Welcome:', user.userName);
    userNameInput.value = user.userName;
    passwordInput.value = user.password;
  }
};

// react to storage changes
storage.onChange(() => {
  let user = storage.getState(stateKey);
  console.log('Local data has changed:', user);

  // if user logged out, auto redirect them to login page
  if (!user) {
    window.location = '/login.html';
  }
});

That's it, some few things to note though, just a few... Starting with never store senstive data in local storage, have an extra layer of security for your applications, we not gonna do that for you in any way!

✍️ Quick Notes For Nerds:

  • For use in SSR or server component react, hacks like use client, typeof window and useEffect still have to be used, otherwise it works well in just client side react apps or plain js apps!
  • useLocalStorage storage unlike the normal broswer localStorage doesnot overwrite state unnecessarily, that is if the state already exists with the same state key, it just updates it instead, otherwise sets it to the new value.
  • The underscore on hook name _useStorage was intentional to prevent hook rules in if say this is used in a react applications, and because we don't obey those rules, this hook does not need to be used in a useEffect to work unlike the normal local storage, this just works, in react or vanilla.

🛠️ Development And Contribution

You noticed a bug, or just want to add in some lines? well just reach out via [email protected] or for developing...

open a terminal and run:

git clone https://github.com/Hussseinkizz/_useLocalStorage

then run pnpm install to install dependencies

lastly run pnpm build to bundle after making changes and then make a PR.

👏 Credits

Hussein Kizz