Skip to main content

useLocalStorage

Get, set and/or remove localStorage.

API

function useLocalStorage<T>(
key: string,
options?: {
defaultValue?: T;
polling?: boolean;
pollingInterval?: number;
compare?: (x: any, y: any) => boolean;
validate?: (value: any) => boolean;
serialize?: (value: T) => string;
deserialize?: (raw: string) => T;
}
): [
value: T | undefined,
setLocalStorage: (
newValue: T | undefined | ((prevValue: T | undefined) => T | undefined)
) => void
];

Params:

  • key: localStorage key.
  • options: Options object.
    • options.defaultValue: Default value.
    • options.polling: Pollingly update value. Default is false.
    • options.pollingInterval: Polling interval time, in milliseconds. Default is 100.
    • options.compare: The comparison function in polling. Use deep comparison by default.
    • options.validate: Validate the value got from localStorage which deserialized by deserialize function. If this function return false, the defaultValue will be used.
    • options.serialize: Serialization function. Default is JSON.stringify.
    • options.deserialize: Deserialization function. Default is JSON.parse.

Results:

  • value: Parsed by the deserialization function.
  • setLocalStorage: Set localStorage. If the newValue is undefined, return the defaultValue.

Example

The value is: default value
import React from "react";
import { useLocalStorage } from "@lilib/hooks";

function Example() {
const [value, setLocalStorage] = useLocalStorage("key", {
polling: true,
defaultValue: "default value",
});

return (
<>
<div>
<button onClick={() => setLocalStorage(Math.random().toString())}>
Set random value
</button>{" "}
<button onClick={() => setLocalStorage(undefined)}>Remove</button>
</div>
<div>The value is: {value}</div>
</>
);
}

export default Example;