Created
October 28, 2019 14:50
-
-
Save csenio/217f3b738c18c60fedb2e54318c7d794 to your computer and use it in GitHub Desktop.
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' | |
function useLocalStorage(key, initialValue) { | |
const [storedValue, setStoredValue] = useState(() => { | |
try { | |
const item = window.localStorage.getItem(key) | |
return item ? JSON.parse(item) : initialValue | |
} catch (error) { | |
return initialValue | |
} | |
}) | |
const setValue = value => { | |
try { | |
const valueToStore = value instanceof Function ? value(storedValue) : value | |
setStoredValue(valueToStore) | |
window.localStorage.setItem(key, JSON.stringify(valueToStore)) | |
} catch (error) { | |
console.error('there was an error setting your data in local storage', error) | |
} | |
} | |
return [storedValue, setValue] | |
} | |
export default useLocalStorage | |
// How To use, | |
/* | |
function App() { | |
const [name, setName] = useLocalStorage('name', 'Bob'); | |
return ( | |
<div> | |
<input | |
type="text" | |
placeholder="Enter your name" | |
value={name} | |
onChange={e => setName(e.target.value)} | |
/> | |
</div> | |
); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment