Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created November 4, 2020 13:45
Show Gist options
  • Save takumifukasawa/7d87a72476c1027bd3858178a1d2cd9f to your computer and use it in GitHub Desktop.
Save takumifukasawa/7d87a72476c1027bd3858178a1d2cd9f to your computer and use it in GitHub Desktop.
React: memolize async value custom hooks
import { DependencyList, useEffect, useState } from "react";
/**
* memolize async value custom hooks
*
* base: https://github.com/awmleer/use-async-memo
*
* usage1: const value = useAsyncMemo(async () => {}, [deps1, dep2, ...]);
* usage2: const value = useAsyncMemo(async () => {}, [deps1, dep2, ...], initialValue);
*
* @export
* @template T
* @param {(() => Promise<T> | undefined | null)} promiseFunc
* @param {DependencyList} deps
* @param {((() => T) | T)} [initialState]
* @returns {(T | (T | undefined))}
*/
export default function useAsyncMemo<T>(
promiseFunc: () => Promise<T> | undefined | null,
deps: DependencyList,
initialState?: (() => T) | T
): T | (T | undefined) {
const [memoValue, setMemoValue] = useState<T | undefined>(initialState);
useEffect(() => {
let aborted = false;
const exec = async () => {
const value = await promiseFunc();
// abort when canceled
if (aborted || !value) {
return;
}
setMemoValue(value);
};
exec();
return () => {
aborted = true;
};
}, deps);
return memoValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment