From 584bd42f871d2e1618ca414749f09c38f0143a44 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Wed, 18 May 2022 22:40:59 +0200
Subject: chore: handle settings change

---
 src/utils/hooks/use-local-storage.tsx | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
 create mode 100644 src/utils/hooks/use-local-storage.tsx

(limited to 'src/utils/hooks/use-local-storage.tsx')

diff --git a/src/utils/hooks/use-local-storage.tsx b/src/utils/hooks/use-local-storage.tsx
new file mode 100644
index 0000000..da0292b
--- /dev/null
+++ b/src/utils/hooks/use-local-storage.tsx
@@ -0,0 +1,35 @@
+import { LocalStorage } from '@services/local-storage';
+import { Dispatch, SetStateAction, useEffect, useState } from 'react';
+
+export type UseLocalStorageReturn<T> = {
+  value: T;
+  setValue: Dispatch<SetStateAction<T>>;
+};
+
+/**
+ * Use the local storage.
+ *
+ * @param {string} key - The storage local key.
+ * @param {T} [fallbackValue] - A fallback value if local storage is empty.
+ * @returns {UseLocalStorageReturn<T>} An object with value and setValue.
+ */
+const useLocalStorage = <T extends unknown>(
+  key: string,
+  fallbackValue: T
+): UseLocalStorageReturn<T> => {
+  const getInitialValue = () => {
+    if (typeof window === 'undefined') return fallbackValue;
+    const storedValue = LocalStorage.get<T>(key);
+    return storedValue || fallbackValue;
+  };
+
+  const [value, setValue] = useState<T>(getInitialValue);
+
+  useEffect(() => {
+    LocalStorage.set(key, value);
+  }, [key, value]);
+
+  return { value, setValue };
+};
+
+export default useLocalStorage;
-- 
cgit v1.2.3

