Haversack
Easy save state management using browser localStorage
or sessionStorage
and React Hooks.
- Written in TypeScript 🎉
- Offers React hooks for both
localStorage
and sessionStorage
🎣 - Set simple key/value pairs or an immutable JSON structure
- JSON state merging
- SSR friendly, Next.js compatible
- Small and performant ⚡️
sessionStorage
is an underrepresented feature as most libraries don't support using either API interchangeably. Storing data to the session is more secure, and is perfectly suitable for many use-cases. Learn about the difference on MDN!
Installation
Install with NPM or Yarn:
npm install --save haversack
yarn add haversack
Usage With React
Haversack exports the two following React hooks, depending on whether you want to use localStorage
or sessionStorage
:
import { useLocalStorage, useSessionStorage } from 'haversack';
Get and Set
Each hook returns an object with the current stored value and a function to update the stored value.
JavaScript
function MyComponent() {
const { value, setValue } = useLocalStorage('myKey');
useEffect(() => {
setValue('updatedValue');
}, []);
return <div>The stored value is {value}</div>;
}
TypeScript
By passing a TypeScript type to the hook, you can enforce a consistent typing for the stored value.
function MyComponent() {
const { value, setValue } = useLocalStorage<string>(
'myKey',
);
useEffect(() => {
setValue('updatedValue');
setValue(5);
}, []);
return <div>The stored value is {value}</div>;
}
Default Value
You can pass an optional default value to the hook. This value will be returned if setValue
has not been called yet.
function MyComponent() {
const defaultValue = 'bar';
const { value } = useLocalStorage('foo', defaultValue);
return (
<div>
The stored value is {value}, but is {defaultValue} by default
</div>
);
}
See notes on SSR compatibility for the server-side behavior of the default value.
Reset the Stored Value
To remove the value from storage, call the resetValue
function. This will return the value to the default if supplied or undefined
if not.
function MyComponent() {
const { value, resetValue } = useLocalStorage('myKey');
return <button onClick={resetValue}>Reset value</button>;
}
Merging State
A unique feature of the library is the ability to manage an immutable store that you can easily merge with updated values.
interface Settings {
name: string;
currentHp: number;
spells?: string[];
}
function MyComponent() {
const {
value: settings,
setValue: writeSettings,
mergeState: updateSettings
} = useLocalStorage<Settings>(
'appSettings',
);
useEffect(() => {
writeSettings({
name: 'Jan Darkmagic',
currentHP: 12,
});
}, []);
const fullRest = () => {
updateSettings({
currentHP: 34,
spells: ['Burning Hands', 'Charm Person'],
});
}
return (
<>
<div>User name: {settings.name}</div>
<button onClick={() => fullRest()}>
Full rest
</button>
</>
);
}
Timestamps
The hooks always return a timestamp
of when the stored value was most recently updated as a JavaScript Date
object.
function MyComponent() {
const { value, timestamp } = useLocalStorage('myKey');
return (
<>
<div>The stored value is {value}</div>
<div>It was updated at: {timestamp.toString()}</div>
</>
);
}
Notes on Server-Side Rendering Compatibility
Obviously browser storage APIs are not functional on the server, and this library is not designed to persist data between the two sources. However, Haversack is built to be friendly with server-side rendered environments including Next.js. If you try to access a stored value on the server, it will return the default value or undefined
if a default is not specified. You should note that if you are rendering the value as text in a React component, this can throw a warning since the server rendered page will mismatch the hydrated client-side render.
If you need functionality to pass state between client and server, you will need something more complex like Redux state management with the Redux Persist library, or an external database.
Known Issues
Placing the haversack inside an extradimensional space created by a bag of holding, portable hole, or similar item instantly destroys both items and opens a gate to the Astral Plane. The gate originates where the one item was placed inside the other. Any creature within 10 feet of the gate is sucked through it and deposited in a random location on the Astral Plane. The gate then closes. The gate is one-way only and can't be reopened.