ReactUseKit

useLocalStorage

A custom hook that manages state synchronized with localStorage.

Installation

pnpm dlx shadcn@latest add https://reactusekit.dev/r/use-local-storage.json

Usage

import { useLocalStorage } from "@/hooks/use-local-storage";

function App() {
  const [theme, setTheme] = useLocalStorage("theme", "light");
  const [name, setName, removeName] = useLocalStorage("userName", "");

  return (
    <div>
      <div>
        <label>Theme: </label>
        <select value={theme} onChange={(e) => setTheme(e.target.value)}>
          <option value="light">Light</option>
          <option value="dark">Dark</option>
        </select>
      </div>
      <div>
        <label>Name: </label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <button onClick={removeName}>Clear</button>
      </div>
      <p>Current theme: {theme}</p>
      <p>Hello, {name || "Guest"}!</p>
    </div>
  );
}

Custom Serializer Example

import { useLocalStorage } from "@/hooks/use-local-storage";

type InstallationType = "cli" | "manual";

function ConfigExample() {
  // Store raw string values without JSON quotes
  const [installType, setInstallType] = useLocalStorage<InstallationType>(
    "installationType",
    "cli",
    {
      serializer: {
        read: (value: string) => (value === "manual" ? "manual" : "cli"),
        write: (value: InstallationType) => value, // Stores "cli" instead of "\"cli\""
      },
    }
  );

  // Custom serializer for dates
  const [lastLogin, setLastLogin] = useLocalStorage("lastLogin", new Date(), {
    serializer: {
      read: (value: string) => new Date(value),
      write: (value: Date) => value.toISOString(),
    },
  });

  return (
    <div>
      <p>Install Type: {installType}</p>
      <button onClick={() => setInstallType("manual")}>Set Manual</button>
      <button onClick={() => setInstallType("cli")}>Set CLI</button>

      <p>Last Login: {lastLogin.toLocaleString()}</p>
      <button onClick={() => setLastLogin(new Date())}>
        Update Login Time
      </button>
    </div>
  );
}

API

Parameters

ParameterTypeDescription
keystringThe localStorage key to use
initialValueTThe initial value if no value exists
optionsobjectConfiguration options

Options

OptionTypeDefaultDescription
serializerobjectJSONCustom serializer with read/write methods
syncDatabooleantrueWhether to sync data across tabs
initializeWithValuebooleantrueWhether to initialize with localStorage value

Returns

NameTypeDescription
valueTThe current value
setValue(value: T | ((val: T) => T)) => voidFunction to set the value
removeValue() => voidFunction to remove the value from storage