feat: add use persisted state hook

This commit is contained in:
clean99 2023-11-20 12:39:58 +08:00
parent 33c856c713
commit 5d1e0a3599

View 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 };