import { useCallback, useEffect, useRef, useState } from "react" import AsyncStorage from "@react-native-async-storage/async-storage" type UseLocalStorageResult = [T, React.Dispatch>] export const useLocalStorage = ( key: string, defaultValue: T, ): UseLocalStorageResult => { const hasSaved = useRef(false) const [value, setValue] = useState(defaultValue) const getFromLocalStorage = useCallback(async (): Promise => { const value = await AsyncStorage.getItem(key) hasSaved.current = true if (value == null) { return defaultValue } return JSON.parse(value) as T }, [key, defaultValue]) useEffect(() => { if (!hasSaved.current) { return } AsyncStorage.setItem(key, JSON.stringify(value)).catch((error) => { console.error(error) }) }, [key, value]) useEffect(() => { getFromLocalStorage() .then((value) => { setValue(value) }) .catch((error) => { setValue(defaultValue) console.error(error) }) }, [defaultValue, getFromLocalStorage]) return [value, setValue] }