Created
September 28, 2020 10:03
-
-
Save aspnetde/44412d47be8d705e9d317ddea36c5b2f to your computer and use it in GitHub Desktop.
A Local Storage React Hook
This file contains hidden or 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
export function useLocalStorage<T>(key: string, initialValue: T) { | |
const [storedValue, setStoredValue] = useState(() => { | |
try { | |
const item = window.localStorage.getItem(key); | |
return item ? (JSON.parse(item) as T) : initialValue; | |
} catch (error) { | |
console.log(error); | |
return initialValue; | |
} | |
}); | |
const setValue = (value: T) => { | |
try { | |
if (value !== undefined) { | |
setStoredValue(value); | |
window.localStorage.setItem(key, JSON.stringify(value)); | |
} else { | |
setStoredValue(initialValue); | |
window.localStorage.removeItem(key); | |
} | |
} catch (error) { | |
console.log(error); | |
} | |
}; | |
return [storedValue, setValue] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment