Type `EffectCallback` – allow async functions?
See original GitHub issueWhen asynchronously downloading data in a useEffect()
callback, it would be nice if we could use an async function (whose return value would be ignored).
// Currently:
const [data, setData] = useState<null | Data>(null);
useEffect(() => {
downloadData()
.then((newData: Data) => {
setData(newData);
});
});
// Wish:
const [data, setData] = useState<null | Data>(null);
useEffect(async () => {
const newData = await downloadData();
setData(newData);
});
Current type:
type EffectCallback = () => void | (() => void);
Suggestion:
type EffectCallback = () => (void | Promise<void> | (() => void));
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (5 by maintainers)
Top Results From Across the Web
How to use async function in React hooks useEffect ...
Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'. Let's see why this error appears by taking the...
Read more >React TypeScript 16.8 How to make useEffect() async
Argument of type '() => Promise' is not assignable to parameter of type 'EffectCallback'. Type 'Promise' is not assignable to type 'void |...
Read more >Successfully using async functions in React useEffect
But by making the useEffect() function an async function, it automatically returns a Promise (even if that promise contains no data).
Read more >How to use async function in useEffect? - DEV Community
In React we all must have used useEffect hook which runs after performing DOM updates and helps us to perform some operation after...
Read more >How to use async function in useEffect hook? | reactpatterns
Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'. Copy. Do you start seeing the problem here?
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@rauschma I get the impression you may have been hinting at something dramatically simpler here though: could we adjust the TS types of
useEffect
/useLayoutEffect
such that returning a Promise is allowed? I think this would be reasonable.~Perhaps to make it clear the return value is unused, we could allow returning
Promise<void>
?~ Edit: now I see you suggested this in your original feature request. Consider that a +1 from me! PR it if you can spare the minute!After extensive discussion we’ve decided not to support this due to the risk of pitfalls