A React hook that provides a SSR-friendly multi-tab persistent state.
npm install @utilityjs/use-persisted-stateA React hook that provides a SSR-friendly multi-tab persistent state.\
(also supports multiple instances with the same key)




``bash`
npm i @utilityjs/use-persisted-state | yarn add @utilityjs/use-persisted-state
`tsx
const App: React.FC = () => {
const [state, setState] = usePersistedState(0, { name: "count" });
return (
API
$3
`ts
type StorageValue = {
state: T;
};interface PersistOptions {
/* Name of the storage (must be unique) /
name: string;
/**
* A function returning a storage.
* The storage must fit
window.localStorage's api.
*
* @default () => localStorage
*/
getStorage?: () => Storage | null;
/**
* Use a custom serializer.
* The returned string will be stored in the storage.
*
* @default JSON.stringify
*/
serializer?: (state: StorageValue) => string;
/**
* Use a custom deserializer.
* Must return an object matching StorageValue
*
* @param str The storage's current value.
* @default JSON.parse
*/
deserializer?: (str: string) => StorageValue;
}declare const usePersistedState: (
initialState: T,
options: PersistOptions
) => [T, React.Dispatch>];
`####
initialStateThe initial value of the state.
####
persistOptionsThe options to adjust the persistence behavior.
#####
persistOptions.nameThe name of the storage (must be unique).
#####
persistOptions.getStorage
###### default: () => localStorage
A function returning a storage. The storage must fit window.localStorage's api.#####
persistOptions.serializer
###### default: JSON.stringify
A custom serializer. The returned string will be stored in the storage.#####
persistOptions.deserializer
###### default: JSON.parse
A custom deserializer. Must return an object matching StorageValue