useLocalState.tsx 647 B

123456789101112131415161718192021222324
  1. import { Dispatch, SetStateAction, useEffect, useState } from 'react';
  2. import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
  3. export function useLocalState<T>(
  4. key: LS_KEYS,
  5. initialValue?: T
  6. ): [T, Dispatch<SetStateAction<T>>] {
  7. const [value, setValue] = useState<T>(initialValue);
  8. useEffect(() => {
  9. const { value } = getData(key) ?? {};
  10. if (typeof value !== 'undefined') {
  11. setValue(value);
  12. }
  13. }, []);
  14. useEffect(() => {
  15. if (typeof value !== 'undefined') {
  16. setData(key, { value });
  17. }
  18. }, [value]);
  19. return [value, setValue];
  20. }