Skip to content

Instantly share code, notes, and snippets.

@denniske
Created June 19, 2025 11:15
Show Gist options
  • Save denniske/e23513bb3c1f6208742c83f69688f85b to your computer and use it in GitHub Desktop.
Save denniske/e23513bb3c1f6208742c83f69688f85b to your computer and use it in GitHub Desktop.
useAsyncStorageValue
function useAsyncStorageValue<T>(key: string) {
const [value, setValue] = useState<T>();
const { getItem, setItem } = useAsyncStorage(key);
const readItemFromStorage = async () => {
const item = await getItem();
setValue(item != null ? JSON.parse(item) : null);
};
const writeItemToStorage = async (newValue: T) => {
await setItem(JSON.stringify(newValue));
setValue(newValue);
};
useEffect(() => {
readItemFromStorage();
}, []);
return [value, writeItemToStorage] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment