Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@codinronan
Created November 29, 2020 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinronan/3d1cecf3f16487393976a2feea5e6942 to your computer and use it in GitHub Desktop.
Save codinronan/3d1cecf3f16487393976a2feea5e6942 to your computer and use it in GitHub Desktop.
React hook: useStorage
// A react hook to generalize the use of any class that implements the Storage interface.
// LocalStorage and SessionStorage are provided here but it is easy to extend to something like
// AsyncStorage for react native.
const useStorage = (key, initialValue, storage) => {
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
try {
const item = storage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
console.error(error)
return initialValue
}
})
useEffect(() => {
try {
// Update storage every time the value is changed
storage.setItem(key, JSON.stringify(storedValue))
} catch (e) {
console.error(e)
}
}, [storedValue, storage, key])
return [storedValue, setStoredValue]
}
export const useLocalStorage = (key, initialValue) => {
return useStorage(key, initialValue, window.localStorage)
}
export const useSessionStorage = (key, initialValue) => {
return useStorage(key, initialValue, window.sessionStorage)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment