aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-local-storage.tsx
blob: 0f9fbb67ffb2b6cb27351d34f91b461c03e284b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { LocalStorage } from '../../services/local-storage';
import { Dispatch, SetStateAction, useEffect, useState } from 'react';

export type UseLocalStorageReturn<T> = {
  value: T;
  setValue: Dispatch<SetStateAction<T>>;
};

/**
 * Use the local storage.
 *
 * @param {string} key - The storage local key.
 * @param {T} [fallbackValue] - A fallback value if local storage is empty.
 * @returns {UseLocalStorageReturn<T>} An object with value and setValue.
 */
export const useLocalStorage = <T,>(
  key: string,
  fallbackValue: T
): UseLocalStorageReturn<T> => {
  const getInitialValue = () => {
    if (typeof window === 'undefined') return fallbackValue;
    const storedValue = LocalStorage.get<T>(key);
    return storedValue ?? fallbackValue;
  };

  const [value, setValue] = useState<T>(getInitialValue);

  useEffect(() => {
    LocalStorage.set(key, value);
  }, [key, value]);

  return { value, setValue };
};