Skip to content

useLocalStorage

Get and Set a specific value in the local storage.

Parameters

  1. the local storage key.
  2. the initial value of the key (default is null).

Return Values

It returns a tuple of 2 values:

IndexNameTypeDescription
0valueAnythe current local storage value.
1setValueFunctionupdate the value.

INFO

When you update a value on the local storage, a StorageEvent will be fired on window.

Example Usage

tsx
import { useLocalStorage } from 'react-pre-hooks';

export default function Example() {
  const [name, setName] = useLocalStorage('name', 'unknown');

  return (
    <main>
      <label htmlFor="name">Name:</label>
      <input id="name" value={name} onChange={e => setName(e.target.value)} />
      <p>Current user name: {name}</p>
    </main>
  );
}
import { useLocalStorage } from 'react-pre-hooks';

export default function Example() {
  const [name, setName] = useLocalStorage('name', 'unknown');

  return (
    <main>
      <label htmlFor="name">Name:</label>
      <input id="name" value={name} onChange={e => setName(e.target.value)} />
      <p>Current user name: {name}</p>
    </main>
  );
}

Released under the MIT License.