Async React useCallback.
Use asynchronous callbacks with useCallback
hook.
This simple function below is simply to illustrate that it is possible. But you can do more than just that, for example calling an API.
This is useful to get out of a “callback hell” scenario using async-await.
function useDelay(time = 1000) {
return React.useCallback(async () => {
return await new Promise((resolve) => {
setTimeout(resolve, time);
});
}, [time]);
}
Please note that this code is for demonstration purposes only. Running delayed().then(() => setState("worked"))
inside the execution phase of a component is not recommended as it will be called every time the component is re-rendered, e.g. when the state changes. In this specific case, the infinite loop is avoided because react doesn’t trigger a re-render on setState when the state remains the same.
Enhancement
Read Using AbortController with Fetch API and ReactJS for how to abort a call and prevent re-renders outside of the lifecycle of the component.