React State Update Tricky Question

🚨 JavaScript + React Interview Question (Tricky) What will be the output? 🤔 import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); setCount(count + 1); setCount(prev => prev + 1); console.log(count); }; return ( <button onClick={handleClick}> Click Me {count} </button> ); } Most developers expect count to increase by 3… 👀 But React doesn’t work that way. 👉 What will be: 1. Console output? 2. Final UI value? Bonus: Why does this happen? 🔥 #ReactJS #FrontendInterview #JavaScript #ReactHooks #ProductBasedCompany

1. 0 2. 2 Because React batches state updates

console log should be 0 , and state value would become 2 , as react state updates are asynchronous in nature, and react do this in batches asynchronously to optimize the UI update performance , render call -> Updated Virtual DOM created - compared with pre updated VDOM -> diffing algo -> update REAL DOM at specific node.

Like
Reply

I was expecting wrong, It is good logical question

See more comments

To view or add a comment, sign in

Explore content categories