Created
June 5, 2023 16:29
-
-
Save emersonbroga/674c9cefbe86f4ff8b53e1f9f4a92d90 to your computer and use it in GitHub Desktop.
Use localStorage Hook for TypeScript
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 { 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