feat: add use persisted state hook
This commit is contained in:
parent
33c856c713
commit
5d1e0a3599
19
frontend/src/hooks/usePersistedState.ts
Normal file
19
frontend/src/hooks/usePersistedState.ts
Normal file
@ -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 };
|
||||
Loading…
Reference in New Issue
Block a user