Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A localStorage drop-in replacement for useState
import { useState } from 'react';
const configureLocalStorage = key => initialValue => {
const [state, setState] = useState(() => {
try {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : initialValue;
} catch (e) {
console.log(e);
return initialValue;
}
}, initialValue);
const storeValue = value => {
const valueToStore = typeof value === 'function' ? value(state) : value;
try {
localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (err) {
console.log(err);
// This space intentionally left blank.
}
setState(valueToStore);
};
return [state, storeValue];
};
export { configureLocalStorage };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.