Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

feat: add use persisted state hook

clean995d1e0a3599c4
diff --git a/frontend/src/hooks/usePersistedState.ts b/frontend/src/hooks/usePersistedState.ts
new file mode 100644
index 00000000..1524ad77
--- /dev/null
+++ b/frontend/src/hooks/usePersistedState.ts
@@ -0,0 +1,19 @@
+import { Dispatch, SetStateAction, useEffect, useState } from 'react';
+
+type PersistedState<T> = [T, Dispatch<SetStateAction<T>>];
+
+function usePersistedState<T>(defaultValue: T, key: string): PersistedState<T> {
+ const [value, setValue] = useState<T>(() => {
+ const value = window.localStorage.getItem(key);
+
+ return value ? (JSON.parse(value) as T) : defaultValue;
+ });
+
+ useEffect(() => {
+ window.localStorage.setItem(key, JSON.stringify(value));
+ }, [key, value]);
+
+ return [value, setValue];
+}
+
+export { usePersistedState };