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