Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

React hook which syncs localStorage[key] with the comp.

License

NotificationsYou must be signed in to change notification settings

rehooks/local-storage

Repository files navigation

All Contributors

React hook for enabling synchronization with local-storage.

npm versionnpm downloads

API Docs can be foundhere.

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.

importReactfrom'react';import{writeStorage}from'@rehooks/local-storage';letcounter=0;constMyButton=()=>(<buttononClick={_=>writeStorage('i',++counter)}>    Click Me</button>);

Read From Storage

This component will receive updates to itself from local storage.

Javascript:

importReactfrom'react';import{useLocalStorage}from'@rehooks/local-storage';functionMyComponent(){const[counterValue]=useLocalStorage('i');// send the key to be tracked.return(<div><h1>{counterValue}</h1></div>);}

Typescript:

importReactfrom'react';import{useLocalStorage}from'@rehooks/local-storage';functionMyComponent(){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 automaticallystringified. This will not work for circular structures.

importReactfrom'react';import{useLocalStorage}from'@rehooks/local-storage';functionMyComponent(){// Note: The type of user can be inferred from the default value typeconst[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 firstdeleteFromStorage('name');// Deletes the itemconstthisIsNull=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 properlysynchronized default value. UsinguseLocalStorage in two different componentswith the same key but different default values can lead to unexpected behaviour.

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

importReact,{createContext,useContext}from'react';import{useLocalStorage}from'@rehooks/local-storage';constdefaultProfile={name:'Spongekebob'};constdefaultContextValue=[defaultProfile,()=>{},()=>{}];constProfileContext=createContext(defaultContextValue);exportconstProfileProvider=({ children})=>{constctxValue=useLocalStorage('profile',defaultProfile);return(<ProfileContext.Providervalue={ctxValue}>{children}</ProfileContext.Provider>);};constuseProfile=()=>useContext(ProfileContext);constApp=()=>{const[profile]=useProfile();return<h1>{profile&&profile.name}</h1>;};exportdefault()=>{return(<ProfileProvider><App/></ProfileProvider>);};

Full Example

You may view this examplehere 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.

importReact,{Fragment}from'react';import{render}from'react-dom';import{writeStorage,deleteFromStorage,useLocalStorage}from'@rehooks/local-storage';conststartingNum=0;constClicker=()=>(<Fragment><h4>Clicker</h4><buttononClick={_=>{writeStorage('num',localStorage.getItem('num')      ?+(localStorage.getItem('num'))+1      :startingNum)}}>      Increment From Outside</button><buttononClick={_=>deleteFromStorage('num')}>      Delete From Outside</button></Fragment>);constIncrememterWithButtons=()=>{const[number,setNum,deleteNum]=useLocalStorage('num');return(<Fragment><p>{typeof(number)==='number' ?number :'Try incrementing the number!'}</p><buttononClick={_=>setNum(number!==null ?+(number)+1 :startingNum)}>Increment</button><buttononClick={deleteNum}>Delete</button></Fragment>);};constApp=()=>(<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):


Amit Solanki

💻📖🤔👀

Joe

💻💡🤔🚧👀⚠️

Fatih Kaya

💻⚠️🐛

Jarl André Hübenthal

💻⚠️🐛

Jamie Kyle

💻

Albert Boehmler

💻🐛

Gabriel Dayley

💻🐛

Harley Alexander

🚧💻🐛⚠️

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

About

React hook which syncs localStorage[key] with the comp.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

[8]ページ先頭

©2009-2025 Movatter.jp