| JavaScript Promises and async/await in React :👈 | 👉:Why Object References Matter in React State |
JavaScript Event Loop Behavior in React |
JavaScript Event Loop Behavior in React
1. Introduction
The JavaScript Event Loop is an important concept for understanding how JavaScript executes code, handles asynchronous operations, and keeps React applications responsive.
In React, the Event Loop plays an important role in:
- Handling button clicks and user interactions.
- Executing API requests and callbacks.
- Managing timers such as
setTimeout(). - Handling Promises and
async/await. - Scheduling React state updates and rendering work.
- Understanding why some UI updates happen after other JavaScript operations.
2. What Is the JavaScript Event Loop?
JavaScript generally executes application code on a single main thread in the browser. This means only one JavaScript task runs at a time on that thread.
However, browsers provide Web APIs to handle operations such as timers, network requests, and user events without blocking JavaScript execution while those operations are waiting.
The Event Loop coordinates when queued JavaScript tasks and Promise callbacks can execute.
Important Components
- Call Stack: Keeps track of currently executing functions.
- Web APIs: Browser facilities that handle operations such as timers, network requests, and DOM events.
- Task Queue (Macrotask Queue): Holds tasks such as timer callbacks and event callbacks.
- Microtask Queue: Holds Promise callbacks and other microtasks.
- Event Loop: Coordinates execution by allowing queued work to run when the call stack is available.
3. Understanding the Event Loop Flow
The following simplified flow shows how JavaScript handles synchronous and asynchronous operations.
Important: After a task finishes, the browser generally processes the microtask queue until it is empty before moving to the next task. Rendering opportunities occur between tasks, according to the browser's scheduling.
4. Call Stack Example
The Call Stack follows the Last In, First Out (LIFO) principle.
function first() {
console.log("First");
second();
}
function second() {
console.log("Second");
}
first();
Output:
First
Second
Execution flow:
first()is added to the Call Stack.console.log("First")executes.second()is added to the Call Stack.console.log("Second")executes.second()finishes and is removed from the stack.first()finishes and is removed from the stack.
5. Synchronous vs Asynchronous JavaScript
Synchronous Example
console.log("Start");
console.log("Middle");
console.log("End");
Output:
Start
Middle
End
Each statement executes in order. The next statement waits until the current statement finishes.
Asynchronous Example
console.log("Start");
setTimeout(() => {
console.log("Timer");
}, 0);
console.log("End");
Output:
Start
End
Timer
Even though the timer delay is zero, its callback is scheduled as a task. It does not execute immediately.
6. Microtask Queue vs Task Queue
JavaScript uses different queues for different types of asynchronous work.
| Microtask Queue | Task Queue |
|---|---|
Promise .then() callbacks |
setTimeout() callbacks |
Promise .catch() callbacks |
setInterval() callbacks |
Promise .finally() callbacks |
Many browser event callbacks |
queueMicrotask() |
Some browser-scheduled tasks |
Microtasks are processed before the browser moves to the next task.
Example: Promise vs setTimeout
console.log("Start");
setTimeout(() => {
console.log("setTimeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
Output:
Start
End
Promise
setTimeout
Why?
- Synchronous statements execute first.
- The Promise callback is placed in the microtask queue.
- The timer callback is scheduled as a task.
- After synchronous execution finishes, the Promise microtask runs.
- The timer callback runs in a later task.
7. How Does async/await Work with the Event Loop?
async/await uses Promises internally. When JavaScript encounters an await expression, the async function pauses until the awaited Promise settles.
console.log("Start");
async function getData() {
console.log("Inside function");
await Promise.resolve();
console.log("After await");
}
getData();
console.log("End");
Output:
Start
Inside function
End
After await
Explanation:
- The synchronous code starts executing.
getData()starts executing.Inside functionis printed.- The function reaches
awaitand pauses. - The remaining synchronous code executes and prints
End. - The continuation after
awaitruns as a microtask.
8. How Does the Event Loop Affect React?
React is built using JavaScript, so React components, event handlers, state updates, and effects execute within the browser's JavaScript environment.
The Event Loop helps determine when JavaScript callbacks execute, while React controls how updates are scheduled, processed, and committed to the UI.
Important React-related areas include:
- State updates using
useState. - Event handlers such as
onClick. - Effects using
useEffect. - Asynchronous API calls.
- Rendering and committing component updates.
9. React State Updates and the Event Loop
Consider the following component:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>
Increment
</button>
</div>
);
}
export default Counter;
When the button is clicked:
- The event handler executes.
setCount(count + 1)requests a state update.console.log(count)reads the value captured by the current render.- React processes the update and renders the component with the new state.
- The updated UI is committed.
Important: Calling a state setter does not immediately change the state variable in the currently executing function. The variable continues to represent the value from that render.
10. React State Updates Are Batched
React can group multiple state updates into a single rendering update. This is called automatic batching.
Example
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const [message, setMessage] = useState("");
function handleClick() {
setCount(count + 1);
setMessage("Updated successfully");
}
return (
<div>
<p>Count: {count}</p>
<p>{message}</p>
<button onClick={handleClick}>
Update
</button>
</div>
);
}
React can process both state updates together and avoid rendering separately for each setter call.
In modern React with React 18 and later using createRoot, automatic batching also applies to updates inside Promise callbacks, timers, and native event handlers.
11. Event Loop and useEffect
useEffect is used to synchronize a component with external systems, such as APIs, subscriptions, and browser features.
React runs an effect after the component has committed its update to the screen. However, the exact timing relative to browser painting can depend on the type of update and scheduling.
Example
import { useEffect, useState } from "react";
function Example() {
const [count, setCount] = useState(0);
console.log("Component rendering");
useEffect(() => {
console.log("useEffect executed");
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
Conceptual sequence after a click:
- The click event handler executes.
- The state update is requested.
- React renders the component.
- React commits the update.
- The effect runs according to React's effect scheduling.
Note: Do not assume that every useEffect always runs after the browser paints. React may run an effect before painting in certain interaction-related situations.
12. Event Loop and API Calls in React
When a React component fetches data from an API, the browser handles the network operation while JavaScript can continue processing other work.
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
async function fetchUsers() {
console.log("API request started");
const response = await fetch("/api/users");
const data = await response.json();
console.log("API response received");
setUsers(data);
}
fetchUsers();
}, []);
return (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
}
Execution flow:
- React commits the component and runs the effect.
- The API request starts.
- The browser handles the network operation.
- JavaScript can execute other tasks while waiting.
- When the response arrives, the Promise continuation becomes eligible to run.
- The response data is processed.
setUsers()requests a React state update.- React renders and commits the updated UI.
13. What Happens When JavaScript Blocks the Main Thread?
JavaScript code that takes a long time to execute can block the main thread.
During this time:
- Button clicks may not respond immediately.
- Animations may become slow.
- React rendering work may be delayed.
- The browser may not get an opportunity to update the screen.
Example of Blocking Code
function handleClick() {
const start = Date.now();
while (Date.now() - start < 5000) {
// Long-running synchronous operation
}
console.log("Completed");
}
This example blocks JavaScript execution for approximately five seconds.
Better approaches:
- Break large tasks into smaller pieces when practical.
- Use Web Workers for suitable CPU-intensive calculations.
- Optimize algorithms and avoid unnecessary calculations.
- Avoid performing expensive synchronous operations during rendering.
14. React Concurrent Rendering and the Event Loop
Modern React includes concurrent rendering capabilities that help React manage rendering work more flexibly.
For example, React can prioritize urgent updates, such as typing into an input, over less urgent updates, such as rendering a large filtered result list.
Important concepts include:
- Concurrent Rendering: React can prepare rendering work in a way that allows it to pause, resume, or abandon certain rendering attempts.
- Transitions: Mark certain updates as non-urgent using
startTransition()oruseTransition(). - Suspense: Allows components to display a fallback while supported resources are loading.
Example: startTransition
import { useState, startTransition } from "react";
function Search() {
const [input, setInput] = useState("");
const [searchTerm, setSearchTerm] = useState("");
function handleChange(event) {
const value = event.target.value;
setInput(value);
startTransition(() => {
setSearchTerm(value);
});
}
return (
<div>
<input
value={input}
onChange={handleChange}
placeholder="Search..."
/>
<p>Search results for: {searchTerm}</p>
</div>
);
}
Here, updating the input is urgent, while updating the search results can be treated as non-urgent.
Important: React concurrent rendering is a React scheduling feature. It does not mean JavaScript can execute multiple functions simultaneously on the same main thread.
15. Common Mistakes
Mistake 1: Assuming setTimeout Executes Immediately
setTimeout(() => {
console.log("Timer");
}, 0);
console.log("End");
Output:
End
Timer
A zero-millisecond timer schedules a callback. It does not execute immediately.
Mistake 2: Assuming Promise Callbacks Run Before Synchronous Code
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("Synchronous");
Output:
Synchronous
Promise
Promise callbacks run as microtasks after the current synchronous execution finishes.
Mistake 3: Assuming State Changes Immediately
setCount(count + 1);
console.log(count);
The console statement reads the state value captured by the current render, not the value requested by the setter.
Mistake 4: Performing Heavy Work During Rendering
Expensive synchronous calculations can block the main thread and make the interface unresponsive.
Mistake 5: Assuming useEffect Has One Fixed Position in the Event Loop
useEffect is scheduled by React after a commit. Its timing relative to painting is not a simple fixed position in the JavaScript task and microtask queues.
16. Best Practices
- Understand the difference between synchronous code, tasks, and microtasks.
- Use Promises and async/await for asynchronous operations.
- Avoid long-running synchronous JavaScript on the main thread.
- Use functional state updates when the next state depends on the previous state.
- Use React transitions for suitable non-urgent UI updates.
- Clean up API requests and subscriptions in effect cleanup functions.
- Do not assume a state setter immediately changes the current state variable.
- Use React DevTools Profiler to investigate expensive rendering.
- Use Web Workers for suitable CPU-intensive operations.
- Remember that React scheduling and the JavaScript Event Loop are related but different mechanisms.
17. Interview Questions and Answers
Q1. What is the JavaScript Event Loop?
The Event Loop coordinates the execution of synchronous JavaScript and queued asynchronous callbacks. It allows queued tasks and microtasks to run when the call stack is available.
Q2. What is the Call Stack?
The Call Stack keeps track of function calls currently being executed. It follows the Last In, First Out (LIFO) principle.
Q3. What is the difference between a microtask and a macrotask?
Microtasks include Promise callbacks and queueMicrotask(). Tasks include timer callbacks and many browser event callbacks. Microtasks are processed before the next task is selected.
Q4. Why does Promise.then() execute before setTimeout()?
Promise callbacks are placed in the microtask queue, while timer callbacks are scheduled as tasks. The microtask queue is processed before the next task runs.
Q5. Does async/await use the Event Loop?
Yes. When an async function reaches an await expression, its continuation is scheduled through Promise-based microtask processing when the awaited Promise settles.
Q6. How does the Event Loop affect React state updates?
React state setters request updates. React schedules and processes those updates, while the JavaScript Event Loop determines when the JavaScript work can execute. The state variable in the current render does not change immediately.
Q7. What is automatic batching in React?
Automatic batching allows React to group multiple state updates into fewer rendering updates. In React 18 and later with createRoot, it also applies to updates from Promises, timers, and native event handlers.
Q8. What happens when the main thread is blocked?
JavaScript cannot process other work on that thread until the blocking operation finishes. User interactions, rendering, and animations may be delayed.
Q9. What is concurrent rendering in React?
Concurrent rendering allows React to manage rendering work flexibly, including pausing, resuming, or abandoning certain rendering attempts. It helps React prioritize urgent UI updates.
Q10. Does React concurrent rendering mean JavaScript runs on multiple threads?
No. Concurrent rendering is a React scheduling capability. JavaScript on the browser's main thread still executes one task at a time.
Q11. What is the difference between useEffect and useLayoutEffect?
useEffect is used for synchronizing with external systems after a component commit. useLayoutEffect runs after DOM mutations but before the browser repaints, making it useful for layout measurements that must happen before painting.
Q12. How can you prevent long-running JavaScript from blocking React?
Optimize calculations, divide suitable work into smaller tasks, avoid expensive operations during rendering, and use Web Workers for CPU-intensive work that can run separately from the main thread.
18. Final Summary
- Call Stack: Executes synchronous JavaScript functions.
- Web APIs: Handle browser operations such as timers and network requests.
- Microtask Queue: Handles Promise callbacks and other microtasks.
- Task Queue: Holds scheduled tasks such as timer callbacks.
- Event Loop: Coordinates when queued work can execute.
- React State: State setters request updates; they do not immediately change the value captured by the current render.
- Automatic Batching: Groups multiple state updates to reduce unnecessary rendering.
- Concurrent Rendering: Allows React to prioritize and manage rendering work flexibly.
- Main Thread: Long-running JavaScript can delay interactions and screen updates.
Remember: The JavaScript Event Loop manages when JavaScript tasks execute, while React manages component updates and rendering. Understanding how these two mechanisms work together helps you build responsive React applications and troubleshoot asynchronous behavior.
| JavaScript Promises and async/await in React :👈 | 👉:Why Object References Matter in React State |
Comments and Discussion