useLocalStorage

A Hook that store state into localStorage.

Examples

Store state into localStorage

Store state into localStorage

Refresh this page and you will get the state from localStorage.

Store complex types of data

a-e-i-o-u

Store complex types such as array or object

useLocalStorageState will do the serialization and deserialization work automatically.

Custom serialization and deserialization functions

Custom serialization and deserialization functions

You may not need the default `JSON.stringifyJSON.parse` to serialize string.

API

If you want to delete this record from localStorage, you can use setState() or setState(undefined).

interface Options<T> {  defaultValue?: T | (() => T);  serializer?: (value: T) => string;  deserializer?: (value: string) => T;  onError?: (error: unknown) => void;  watch?: boolean}const [state, setState] = useLocalStorage<T>(  key: string,  options: Options<T>): [Accessor<T>, (value?: Setter<T>) => void];
interface Options<T> {  defaultValue?: T | (() => T);  serializer?: (value: T) => string;  deserializer?: (value: string) => T;  onError?: (error: unknown) => void;  watch?: boolean}const [state, setState] = useLocalStorage<T>(  key: string,  options: Options<T>): [Accessor<T>, (value?: Setter<T>) => void];

Result

PropertyDescriptionType
stateLocal localStorage valueAccessor<T>
setStateUpdate localStorage valueSetter<T>

Options

PropertyDescriptionTypeDefault
defaultValueDefault valueany | (() => any)-
serializerCustom serialization method(value: any) => stringJSON.stringify
deserializerCustom deserialization method(value: string) => anyJSON.parse
onErrorOn error callback(error: unknown) => void(e) => { console.error(e) }
observerWatch changesbooleanfalse

Remark

useLocalStorageState will call serializer before write data to localStorage, and call deserializer once after read data.