Created
June 22, 2021 22:37
-
-
Save banjeremy/ec6f970174add7d40c5183c0ceafd999 to your computer and use it in GitHub Desktop.
useLocalStorage
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 { 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