Intermediate LevelReact JS & React 19
How do JavaScript Microtasks and Macrotasks interact with React state batching and rendering?
❓ Interview Prompt: Explain Event Loop microtask queue (`Promise.then`, `queueMicrotask`) vs macrotask queue (`setTimeout`), and React render timing.
React's batching mechanism interacts closely with the JavaScript Event Loop:
•
Microtasks ('Promise.then', 'queueMicrotask'): Processed immediately after the current script task before yielding to the browser paint loop.
•
Macrotasks ('setTimeout', 'setInterval'): Scheduled for future event loop ticks after browser painting.
•
In React 18+, state updates triggered inside both microtasks and macrotasks are automatically batched!
Code Implementation Example
jsx
function EventLoopBatching() {
const [val, setVal] = useState(0);
const handleMicrotask = () => {
queueMicrotask(() => {
// Microtask execution: Batched in React 18+!
setVal(1);
});
};
}💡Scheduling microtask state updates with queueMicrotask.
🎯 Interview Key Takeaway
React 18+ automatically batches state updates scheduled inside event loop microtasks and macrotasks.
#Event Loop#Microtasks#Batching#Intermediate
Back to all React JS & React 19 Questions→