Custom React hooks for keeping application state in sync with localStorage and sessionStorage.
📖 Familiar API. You already know how to use this library! Replace the useState and useReducer hooks with the ones in this library and get persistent state for free.
✨ Fully featured. Automatically stringifies and parses values coming and going to storage, keeps state in sync between tabs by listening to storage events and handles non-straightforward use cases correctly. Also supports server-side rendering. Expect it to just work.
⚡ Tiny and fast. Less than 1kb gzipped. No external dependencies. Only reads from storage when necessary and always updates application state before writing.
🔠 Completely typed. Written in TypeScript. Type definitions included.
💪 Backed by tests. Full coverage of the whole API.
Since this library provides custom React hooks, you need a working React environment. I recommend the official Create React App.
Add the library to your project with npm:
npm install --save react-storage-hooks
Or with yarn:
yarn add react-storage-hooks
And import the hooks to use them:
import {
useLocalStorageState,
useLocalStorageReducer,
useSessionStorageState,
useSessionStorageReducer,
} from 'react-storage-hooks';Four hooks are included:
- For
localStorage:useLocalStorageStateanduseLocalStorageReducer. - For
sessionStorage:useSessionStorageStateanduseSessionStorageReducer.
They mirror the API of React's built-in useState and useReducer hooks. Please read their docs to learn how to use them, and don't hesitate to file an issue if you happen to find diverging behavior.
The only but important differences are:
- You need to provide a storage key as an additional first parameter. This is mandatory.
- The initial state parameter only applies if there's no data in storage for the provided key. Otherwise the storage data will be used. Think of it as a default state.
- The array returned by the hooks has an extra last item for write errors. It is initially
undefined, and will be updated withErrorobjects thrown byStorage.setItem. However the hook will keep updating state even if new values fail to be written to storage, to ensure that your application doesn't break.
useState hooks with localStorage or sessionStorage persistence.
const [state, setState, writeError] = useLocalStorageState(key, defaultState?);
const [state, setState, writeError] = useSessionStorageState(key, defaultState?);import React from 'react';
import { useLocalStorageState } from 'react-storage-hooks';
const Counter = () => {
const [count, setCount, writeError] = useLocalStorageState('counter', 0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(0)}>Reset</button>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
{writeError && (
<pre>Cannot write to localStorage: {writeError.message}</pre>
)}
</div>
);
};useReducer hooks with localStorage or sessionStorage persistence.
const [state, dispatch, writeError] = useLocalStorageReducer(
key,
reducer,
initializerArg,
initializer?
);
const [state, dispatch, writeError] = useSessionStorageReducer(
key,
reducer,
initializerArg,
initializer?
);import React from 'react';
import { useLocalStorageReducer } from 'react-storage-hooks';
const initialCount = 0;
const reducer = (state, action) => {
switch (action.type) {
case 'reset':
return { count: initialCount };
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const Counter = () => {
const [state, dispatch, writeError] = useLocalStorageReducer(
'counter',
reducer,
{
count: initialCount,
}
);
return (
<div>
<p>You clicked {state.count} times</p>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
{writeError && (
<pre>Cannot write to localStorage: {writeError.message}</pre>
)}
</div>
);
};