Created
November 29, 2020 03:17
-
-
Save codinronan/3d1cecf3f16487393976a2feea5e6942 to your computer and use it in GitHub Desktop.
React hook: useStorage
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
// 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