Skip to content

Instantly share code, notes, and snippets.

@gragland
Created October 29, 2018 04:20
Show Gist options
  • Save gragland/072dbaf3a94b525e22040fd02d3b814c to your computer and use it in GitHub Desktop.
Save gragland/072dbaf3a94b525e22040fd02d3b814c to your computer and use it in GitHub Desktop.
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