Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Created March 30, 2020 23:34
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ericelliott/0d3428142d1f106369c6d82210e3a2b9 to your computer and use it in GitHub Desktop.
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