useLocalStorage

A custom React hook to manage state synchronized with `localStorage`.
> useLocalStorage<T>(key: string, initialValue: T,
      options?: {
        serialize?: (value: T) => string;
        deserialize?: (value: string) => T;
      }):
       readonly [T, (value: T | ((prev: T) => T)) => void]
Parameters
  • key: The key to use when storing and retrieving the value in `localStorage`.
  • initialValue: The default value to use if there is no value in `localStorage` or if an error occurs.
  • options: An optional object with the following properties:
    • serialize: A function to convert the value to a string for storage. Defaults to `JSON.stringify`.
    • deserialize: A function to parse the stored string back into the original value. Defaults to `JSON.parse`.
  • Returns: A tuple containing the current value and a function to update the value in `localStorage`.

Example

import { useLocalStorage } from "daily-toolset/hooks";

function App() {
  const [name, setName] = useLocalStorage("name", "Guest");

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter your name"
      />
    </div>
  );
}

// Custom serialization/deserialization example
const [userPreferences, setUserPreferences] = useLocalStorage("prefs", {}, {
  serialize: (value) => btoa(JSON.stringify(value)), // Encode as base64
  deserialize: (value) => JSON.parse(atob(value)), // Decode from base64
});

Use Cases

  • Persisting user preferences across sessions, such as theme or language settings.
  • Storing form inputs to prevent loss of progress during a page refresh.
  • Synchronizing application state with browser `localStorage` for lightweight data storage.