Skip to content

useLocalStorageState ​

A Hook that store state into localStorage.

Code demonstration ​

Basic usage ​

Advanced usage ​

API ​

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

typescript
interface Options<T> {
  defaultValue?: T | (() => T);
  serializer?: (value: T) => string;
  deserializer?: (value: string) => T;
}
const [state, setState] = useLocalStorageState<T>(
  key: string,
  options: Options<T>
): [T?, (value?: T | ((previousState: T) => T)) => void];

Options ​

PropertyDescriptionTypeDefault
defaultValueDefault valueany | (() => any)-
serializerCustom serialization method(value: any) => stringJSON.stringify
deserializerCustom deserialization method(value: string) => anyJSON.parse

Result ​

PropertyDescriptionType
stateLocal Storage-valueRef<any | undefined>
setStateSet Storage valueSetState

Remark

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

Source ​

Source · Document · Demo

Released under the MIT License.