Skip to content

Latest commit

Β 

History

History
41 lines (33 loc) Β· 1.1 KB

useLocalStorage.md

File metadata and controls

41 lines (33 loc) Β· 1.1 KB

useLocalStorage

React side-effect hook that manages a single localStorage key.

Usage

import { useLocalStorage } from 'react-use';

const Demo = () => {
  const [value, setValue, remove] = useLocalStorage('my-key', 'foo');

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue('bar')}>bar</button>
      <button onClick={() => setValue('baz')}>baz</button>
      <button onClick={() => remove()}>Remove</button>
    </div>
  );
};

Reference

useLocalStorage(key);
useLocalStorage(key, initialValue);
useLocalStorage(key, initialValue, { raw: true });
useLocalStorage(key, initialValue, {
  raw: false,
  serializer: (value: T) => string,
  deserializer: (value: string) => T,
});
  • key β€” localStorage key to manage.
  • initialValue β€” initial value to set, if value in localStorage is empty.
  • raw β€” boolean, if set to true, hook will not attempt to JSON serialize stored values.
  • serializer β€” custom serializer (defaults to JSON.stringify)
  • deserializer β€” custom deserializer (defaults to JSON.parse)