React hook for enabling synchronization with local-storage.
API Docs can be found here.
- 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
yarn add @rehooks/local-storagenpm i @rehooks/local-storage --saveThis 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>);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>);}Note: Objects that are passed to useLocalStorage's default parameter will be automatically stringified. 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>);}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 nullIt 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).
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>);};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.
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'));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 the all-contributors specification. Contributions of any kind welcome!