aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/useLocalStorage.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/hooks/useLocalStorage.ts')
-rw-r--r--src/hooks/useLocalStorage.ts30
1 files changed, 30 insertions, 0 deletions
diff --git a/src/hooks/useLocalStorage.ts b/src/hooks/useLocalStorage.ts
new file mode 100644
index 0000000..5893317
--- /dev/null
+++ b/src/hooks/useLocalStorage.ts
@@ -0,0 +1,30 @@
+import { useState, useCallback } from 'react';
+
+function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void] {
+ const [storedValue, setStoredValue] = useState<T>(() => {
+ try {
+ const item = window.localStorage.getItem(key);
+ return item ? JSON.parse(item) : initialValue;
+ } catch (error) {
+ console.log(error);
+ return initialValue;
+ }
+ });
+
+ const setValue = useCallback((value: T) => {
+ setStoredValue((originalValue: T) => {
+ try {
+ const valueToStore = value instanceof Function ? value(originalValue) : value;
+ window.localStorage.setItem(key, JSON.stringify(valueToStore));
+ return valueToStore;
+ } catch (error) {
+ console.log(error);
+ }
+ });
+ }, [key]);
+
+ return [storedValue, setValue];
+}
+
+export default useLocalStorage;
+