Skip to content

Instantly share code, notes, and snippets.

@aapzu
Created November 25, 2019 15:13
Show Gist options
  • Save aapzu/5d09d53cb8dab37cb95be7fdc50d750e to your computer and use it in GitHub Desktop.
Save aapzu/5d09d53cb8dab37cb95be7fdc50d750e to your computer and use it in GitHub Desktop.
useLocalStorage.ts
import { useState } from "react"
// tslint:disable-next-line:no-any
export const useLocalStorage = <T extends any>(key: string, initialValue: T) => {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
// Get from local storage by key
const item = window.localStorage.getItem(key)
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue
} catch (error) {
// If error also return initialValue
console.log(error)
return initialValue
}
})
const setValue = (value: T) => {
try {
setStoredValue(value)
window.localStorage.setItem(key, JSON.stringify(value))
} catch (error) {
console.log(error)
}
}
return [storedValue, setValue]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment