Created
October 30, 2018 09:48
-
-
Save LeeCheneler/f3aa689a58eb06342cb5ca385fe06890 to your computer and use it in GitHub Desktop.
useLocalStorage React Hook
This file contains hidden or 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, useEffect } from 'react'; | |
// Usage | |
function App() { | |
// Similar to useState but we pass in a key to value in local storage | |
// With useState: const [name, setName] = useState('Bob'); | |
const [name, setName] = useLocalStorage('name', 'Bob'); | |
return ( | |
<div> | |
<input | |
type="text" | |
placeholder="Enter your name" | |
value={name} | |
onChange={e => setName(e.target.value)} | |
/> | |
</div> | |
); | |
} | |
// Hook | |
function useLocalStorage(key, initialValue) { | |
// The initialValue arg is only used if there is nothing in local storage ... | |
// ... otherwise we use the value in local storage so state persist through a page refresh. | |
// We pass a function to useState so local storage lookup only happens once. | |
const [item, setValue] = useState( | |
() => window.localStorage.getItem(key) || initialValue | |
); | |
useEffect(() => { | |
window.localStorage.setItem(key, item); | |
}); | |
return [item, setValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment