useEffect, promises and setTimeout.
Several useEffect hooks with an empty dependency array, some awaiting promises and some setting timers. What order do the logs come out in, and why?
useEffect with an empty dependency array is the familiar way to run code once, after a component mounts. But what happens when a component has several of them, one awaiting a promise and another setting a timer? The order the logs come out in can be surprising until you look at the event loop.
Let's go through a few combinations.
Example 1: a slow promise and an immediate timer
import React, { useEffect } from "react";
function App() {
useEffect(() => {
console.log("Effect 1: Promise starts");
(async () => {
await new Promise((resolve) => setTimeout(resolve, 2000)); // a 2 second task
console.log("Effect 1: Promise resolved");
})();
}, []);
useEffect(() => {
console.log("Effect 2: setTimeout scheduled");
setTimeout(() => {
console.log("Effect 2: setTimeout executed");
}, 0);
}, []);
return <div>Check the console!</div>;
}Effect 1: Promise starts
Effect 2: setTimeout scheduled
Effect 2: setTimeout executed
Effect 1: Promise resolvedWhy:
- React runs the effects in the order they are written, so both first lines print straight away.
- The promise in Effect 1 is waiting on a 2 second timer. Until that timer fires, nothing is queued for it.
- The timer in Effect 2 is due after 0 ms, so its callback runs first.
- Two seconds later the first timer fires and resolves the promise, and the code after
awaitruns.
The promise here is only as fast as the timer inside it.
Example 2: a fast promise and a slow timer
useEffect(() => {
console.log("Effect 3: Fast Promise starts");
(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
console.log("Effect 3: Fast Promise resolved");
})();
}, []);
useEffect(() => {
console.log("Effect 4: Slow setTimeout scheduled");
setTimeout(() => {
console.log("Effect 4: Slow setTimeout executed");
}, 100);
}, []);Effect 3: Fast Promise starts
Effect 4: Slow setTimeout scheduled
Effect 3: Fast Promise resolved
Effect 4: Slow setTimeout executedSame rule, other way round. The 0 ms timer fires first and resolves the promise, so the code after await runs well before the 100 ms timer.
Example 3: three effects with different timing
useEffect(() => {
console.log("Effect 5: Medium Promise starts");
(async () => {
await new Promise((resolve) => setTimeout(resolve, 500));
console.log("Effect 5: Medium Promise resolved");
})();
}, []);
useEffect(() => {
console.log("Effect 6: Immediate setTimeout scheduled");
setTimeout(() => {
console.log("Effect 6: Immediate setTimeout executed");
}, 0);
}, []);
useEffect(() => {
console.log("Effect 7: Long Promise starts");
(async () => {
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log("Effect 7: Long Promise resolved");
})();
}, []);Effect 5: Medium Promise starts
Effect 6: Immediate setTimeout scheduled
Effect 7: Long Promise starts
Effect 6: Immediate setTimeout executed
Effect 5: Medium Promise resolved
Effect 7: Long Promise resolvedThe three effects start in order. After that it is just the timers: 0 ms, then 500 ms, then 1000 ms.
The interesting one: a resolved promise and a 0 ms timer
So far the timers decided everything. What if the promise is not waiting on a timer at all?
useEffect(() => {
console.log("Effect 8: Quick Promise starts");
(async () => {
await Promise.resolve(); // already resolved
console.log("Effect 8: Quick Promise resolved");
})();
}, []);
useEffect(() => {
console.log("Effect 9: Immediate setTimeout scheduled");
setTimeout(() => {
console.log("Effect 9: Immediate setTimeout executed");
}, 0);
}, []);Effect 8: Quick Promise starts
Effect 9: Immediate setTimeout scheduled
Effect 8: Quick Promise resolved
Effect 9: Immediate setTimeout executedThis is where the two queues matter. The code after await is a microtask. A timer callback is a task (often called a macrotask). After the current code finishes, JavaScript runs every waiting microtask before it picks up the next task. So the promise wins, even against a timer with no delay.
Key takeaways
- Order of effects. React runs
useEffectcallbacks in the order they are written, after the render is on screen. - Effects are synchronous unless the code inside them makes them asynchronous.
- Microtasks before tasks. Code after
awaiton an already-settled promise runs before any timer callback, includingsetTimeout(fn, 0). - A promise that waits on a timer resolves when that timer fires, and no sooner.
- Empty dependency array. The effect runs once, on mount. In development with Strict Mode, React mounts the component twice, so you will see every log twice.