Skip to content

Instantly share code, notes, and snippets.

@emersonbroga
Created June 5, 2023 16:29
Show Gist options
  • Save emersonbroga/674c9cefbe86f4ff8b53e1f9f4a92d90 to your computer and use it in GitHub Desktop.
Save emersonbroga/674c9cefbe86f4ff8b53e1f9f4a92d90 to your computer and use it in GitHub Desktop.
Use localStorage Hook for TypeScript
import { useState, useEffect } from 'react'
const getStorageValue = <T>(key: string, defaultValue?: T): T | undefined => {
const fallback = defaultValue || undefined
if (typeof window === 'undefined') return fallback
const value = localStorage.getItem(key)
if (value === null) return fallback
try {
return JSON.parse(value)
} catch (err) {
return fallback
}
}
const setStorageValue = <T>(key: string, value: T): T | undefined => {
if (typeof window === 'undefined') return undefined
localStorage.setItem(key, JSON.stringify(value))
return value
}
const removeStorageValue = (key: string): undefined => {
if (typeof window === 'undefined') return
localStorage.removeItem(key)
}
export const useLocalStorage = function <T>(
key: string,
defaultValue?: T
): {
value: T | undefined
setValue: React.Dispatch<T>
removeValue: (key: string) => undefined
} {
const [value, setValue] = useState(() => {
return getStorageValue(key, defaultValue)
})
const removeValue = (key: string): undefined => removeStorageValue(key)
useEffect(() => {
setStorageValue(key, value)
}, [key, value])
return {
value,
setValue,
removeValue,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment