ente/packages/shared/hooks/useLocalState.tsx

25 lines
647 B
TypeScript
Raw Normal View History

2022-04-29 11:13:45 +00:00
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
2023-11-09 04:10:43 +00:00
import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
2022-04-29 11:13:45 +00:00
export function useLocalState<T>(
key: LS_KEYS,
initialValue?: T
): [T, Dispatch<SetStateAction<T>>] {
const [value, setValue] = useState<T>(initialValue);
2022-04-29 11:13:45 +00:00
useEffect(() => {
const { value } = getData(key) ?? {};
if (typeof value !== 'undefined') {
setValue(value);
}
2022-04-29 11:13:45 +00:00
}, []);
useEffect(() => {
2022-06-27 00:48:07 +00:00
if (typeof value !== 'undefined') {
setData(key, { value });
}
2022-04-29 11:13:45 +00:00
}, [value]);
return [value, setValue];
}