Created
October 29, 2018 04:20
-
-
Save gragland/072dbaf3a94b525e22040fd02d3b814c 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'; | |
// Usage | |
function App() { | |
const [name, setName] = useLocalStorage('name', ''); | |
return ( | |
<div> | |
<input | |
type="text" | |
placeholder="Enter your name" | |
value={name} | |
onChange={e => setName(e.target.value)} | |
/> | |
</div> | |
); | |
} | |
// Hook | |
function useLocalStorage(key, initialValue) { | |
// The initial state we pass to useState should come from ... | |
// ... local storage if a value has been set. | |
const initialState = | |
window.localStorage.getItem(key) !== null | |
? window.localStorage.getItem(key) | |
: initialValue; | |
const [item, setValue] = useState(initialState); | |
// Updates both our state and local storage | |
const setItem = item => { | |
setValue(item); | |
window.localStorage.setItem(key, item); | |
}; | |
return [item, setItem]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment