React side-effect hook that manages a single localStorage
key.
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>
);
};
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 inlocalStorage
is empty.raw
— boolean, if set totrue
, hook will not attempt to JSON serialize stored values.serializer
— custom serializer (defaults toJSON.stringify
)deserializer
— custom deserializer (defaults toJSON.parse
)