useLocalState.tsx 677 B

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