Skip to main content

useLocalStorage

React side-effect hook that manages a single localStorage key

Usage

Live Editor

function Demo() {
  // bind string
  const [value, setValue] = useLocalStorage("my-key", "key");

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue("bar")}>bar</button>
      <button onClick={() => setValue("baz")}>baz</button>
      {/* delete data from storage */}
      <button onClick={() => setValue(null)}>Remove</button>
    </div>
  );
};

Result
Loading...

API

useLocalStorage

Returns

readonly [T | null, React.Dispatch<React.SetStateAction<T | null>>]: A tuple with the following elements:

  • The current value of the localStorage.
  • A function to update the value of the localStorage.

Arguments

ArgumentDescriptionTypeDefaultValue
keykeystring (Required)-
defaultValuedefault valueT | undefined-
optionsoptional paramsUseLocalStorageOptions<T> | undefined-

UseLocalStorageOptions

PropertyDescriptionTypeDefaultValue
serializerCustom data serializationUseLocalStorageSerializer<T>-
onErrorOn error callback(error: unknown) => voidconsole.error
effectStorageValueset to storage when nodata in first mount, deprecatedT | (() => T)-
mountStorageValueset to storage when nodata in first mountT | (() => T)-
listenToStorageChangeslisten to storage changesbooleantrue

UseLocalStorageSerializer

PropertyDescriptionTypeDefaultValue
readCustom data read(raw: string) => T (Required)-
writeCustom data write(value: T) => string (Required)-