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

@rehooks/local-storage

v2.4.5

Published

React hook for local-storage

Downloads

188,227

Readme

@rehooks/local-storage

All Contributors

React hook for enabling synchronization with local-storage.

npm version npm downloads

API Docs can be found here.

Table of Contents

Features

  • Automatic JSON serialization
  • Synchronization across multiple tabs
  • Provides functions for updating the localStorage and triggering a state update outside of the component
  • Type hinting via TypeScript

Install

With Yarn

yarn add @rehooks/local-storage

With NPM

npm i @rehooks/local-storage --save

Usage

Write to Storage

This can be anywhere from within your application.

Note: Objects that are passed to writeStorage are automatically stringified. This will not work for circular structures.

import React from 'react';
import { writeStorage } from '@rehooks/local-storage';

let counter = 0;

const MyButton = () => (
  <button onClick={_ => writeStorage('i', ++counter)}>
    Click Me
  </button>
);

Read From Storage

This component will receive updates to itself from local storage.

Javascript:

import React from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

function MyComponent() {
  const [counterValue] = useLocalStorage('i'); // send the key to be tracked.
  return (
    <div>
      <h1>{counterValue}</h1>
    </div>
  );
}

Typescript:

import React from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

function MyComponent() {
  const [counterValue] = useLocalStorage<number>('i'); // specify a type argument for your type
  // Note: Since there was no default value provided, this is potentially null.
  return (
    <div>
      <h1>{counterValue}</h1>
    </div>
  );
}

Optionally use a default value

Note: Objects that are passed to useLocalStorage's default parameter will be automatically stringified. This will not work for circular structures.

import React from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

function MyComponent() {
  // Note: The type of user can be inferred from the default value type
  const [user] = useLocalStorage('user', { name: 'Anakin Skywalker' });
  return (
    <div>
      <h1>{user.name}</h1>
    </div>
  );
}

Delete From Storage

You may also delete items from the local storage as well.

import { writeStorage, deleteFromStorage } from '@rehooks/local-storage';

writeStorage('name', 'Homer Simpson'); // Add an item first

deleteFromStorage('name'); // Deletes the item

const thisIsNull = localStorage.getItem('name'); // This is indeed null

Using With Context

It is advisable to use this hook with context if you want to have a properly synchronized default value. Using useLocalStorage in two different components with the same key but different default values can lead to unexpected behaviour.

Using Context will also prevent components from rendering and setting default values to the localStorage when you just want them to be deleted from localStorage (assuming the context provider also does not re-render).

import React, { createContext, useContext } from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

const defaultProfile = { name: 'Spongekebob' };
const defaultContextValue = [defaultProfile, () => {}, () => {}];

const ProfileContext = createContext(defaultContextValue);

export const ProfileProvider = ({ children }) => {
  const ctxValue = useLocalStorage('profile', defaultProfile);
  return (
    <ProfileContext.Provider value={ctxValue}>
      {children}
    </ProfileContext.Provider>
  );
};

const useProfile = () => useContext(ProfileContext);

const App = () => {
  const [profile] = useProfile();
  return <h1>{profile && profile.name}</h1>;
};

export default () => {
  return (
    <ProfileProvider>
      <App />
    </ProfileProvider>
  );
};

Full Example

You may view this example here on StackBlitz.

Note: The writeStorage and deleteFromStorage functions are provided from useLocalStorage as well, and do not require you to specify the key when using them.

import React, { Fragment } from 'react';
import { render } from 'react-dom';
import { writeStorage, deleteFromStorage, useLocalStorage } from '@rehooks/local-storage';

const startingNum = 0;

const Clicker = () => (
  <Fragment>
    <h4>Clicker</h4>
    <button onClick={_ => {
      writeStorage('num', localStorage.getItem('num')
      ? +(localStorage.getItem('num')) + 1
      : startingNum
      )
    }}>
      Increment From Outside
    </button>
    <button onClick={_ => deleteFromStorage('num')}>
      Delete From Outside
    </button>
  </Fragment>
);

const IncrememterWithButtons = () => {
  const [number, setNum, deleteNum] = useLocalStorage('num');

  return (
    <Fragment>
      <p>{typeof(number) === 'number' ? number : 'Try incrementing the number!'}</p>
      <button onClick={_ => setNum(number !== null ? +(number) + 1 : startingNum)}>Increment</button>
      <button onClick={deleteNum}>Delete</button>
    </Fragment>
  );
};

const App = () => (
  <Fragment>
    <h1> Demo </h1>
    <IncrememterWithButtons />
    <Clicker />
  </Fragment>
);

// Assuming there is a div in index.html with an ID of 'root'
render(<App />, document.getElementById('root'));

Contributors ✨

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!