Created
March 30, 2020 23:34
Star
You must be signed in to star a gist
A localStorage drop-in replacement for useState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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