Skip to content

Instantly share code, notes, and snippets.

@banjeremy
Created June 22, 2021 22:37
Show Gist options
  • Save banjeremy/ec6f970174add7d40c5183c0ceafd999 to your computer and use it in GitHub Desktop.
Save banjeremy/ec6f970174add7d40c5183c0ceafd999 to your computer and use it in GitHub Desktop.
useLocalStorage
import { useCallback, useState } from 'react';
// like `useState`, but also persists to local storage
export default function useLocalStorage<T>(key: string, initialValue: T): [T, (initialValue: T) => void] {
const [state, setState] = useState<T>(() => {
try {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : initialValue;
} catch (e) {
return initialValue;
}
});
const set = useCallback((key: string, value: T) => {
localStorage.setItem(key, JSON.stringify(value));
setState(value);
}, []);
return [state, (value: T) => set(key, value)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment