Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Created October 30, 2018 09:48
Show Gist options
  • Save LeeCheneler/f3aa689a58eb06342cb5ca385fe06890 to your computer and use it in GitHub Desktop.
Save LeeCheneler/f3aa689a58eb06342cb5ca385fe06890 to your computer and use it in GitHub Desktop.
useLocalStorage React Hook
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