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 isfalse
.options.pollingInterval
: Polling interval time, in milliseconds. Default is100
.options.compare
: The comparison function in polling. Use deep comparison by default.options.validate
: Validate the value got fromlocalStorage
which deserialized bydeserialize
function. If this function returnfalse
, thedefaultValue
will be used.options.serialize
: Serialization function. Default isJSON.stringify
.options.deserialize
: Deserialization function. Default isJSON.parse
.
Results:
value
: Parsed by the deserialization function.setLocalStorage
: SetlocalStorage
. If thenewValue
isundefined
, return thedefaultValue
.
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;