Created
December 12, 2022 12:57
-
-
Save Kyoss79/2157b207b0988a3019be51b2f8cbbd39 to your computer and use it in GitHub Desktop.
React 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 { useState } from 'react'; | |
export const useLocalStorage = <ValueType>( | |
keyName: string, | |
defaultValue?: ValueType, | |
deserialize = JSON.parse, | |
serialize = JSON.stringify | |
): [ValueType | undefined, (newValue: ValueType) => void] => { | |
const [storedValue, setStoredValue] = useState<ValueType | undefined>(() => { | |
const value = globalThis.localStorage?.getItem(keyName); | |
if (value !== null) { | |
try { | |
return deserialize(value) as ValueType; | |
} catch { | |
return defaultValue; | |
} | |
} | |
if (typeof defaultValue !== 'undefined') { | |
globalThis.localStorage?.setItem(keyName, serialize(defaultValue)); | |
} | |
return defaultValue; | |
}); | |
const setValue = (newValue: ValueType): void => { | |
if (typeof newValue === 'string') { | |
globalThis.localStorage?.setItem(keyName, newValue); | |
} else { | |
try { | |
globalThis.localStorage?.setItem(keyName, serialize(newValue)); | |
} catch { | |
throw new Error(`Failed to set ${keyName} in local storage.`); | |
} | |
} | |
setStoredValue(newValue); | |
}; | |
return [storedValue, setValue]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment