HooksuseLocalStorage

useLocalStorage()

The useLocalStorage() hook acts like useState but persists the value to the browser‘s localStorage. It automatically parses JSON values and synchronizes state updates across other tabs and windows.

Import

typescript
import { useLocalStorage } from 'the-react-hooks';

Usage

Persisted Counter
0
Persisted Input

Values persist even after page reload!

Component.tsx
import { useLocalStorage } from 'the-react-hooks';

export const Component = () => {
  const [name, setName] = useLocalStorage('user-name', 'Guest');

  return (
    <div>
      <p>Hello, {name}!</p>
      <input 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
      />
    </div>
  );
}

API

Arguments

  • key string The key name used to store the value in localStorage.
  • initialValue T The initial value to use if no value is currently stored in localStorage.

Returns

Returns a standard state tuple:
  • [0] value T The current persisted value (or initial value).
  • [1] setValue (value: T | ((val: T) => T)) => void Function to update the state and localStorage.