react-usekit

Beta

useLocalStorage

A custom hook that manages state synchronized with localStorage.

Installation

npx react-usekit@latest init

Select: hooks → TypeScript or JavaScript → path -> useLocalStorage

Usage

import { useLocalStorage } from "./hooks/useLocalStorage";

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>
  );
}

API

Parameters

ParameterTypeDefaultDescription
keystring-The localStorage key to use
initialValueT-The initial value if no value exists
optionsobject{}Configuration 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