Join the discussion
Comments
Loading comments...
Cookie preferences
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Join the discussion
Loading comments...
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
React performance ke liye kai setState calls ko ek hi re-render mein kaise batch karta hai.
State batching ka matlab hai React ek hi synchronous block se multiple setState calls collect karta hai aur unhe sab ek single re-render pass mein process karta hai. Har individual setState ke baad re-render karne ki jagah, React current 'batch' ke end tak wait karta hai, saare updates ek saath apply karta hai, aur exactly ek baar render karta hai. React 18 ne automatic batching ko async code aur native event listeners tak bhi extend kar diya.
Jab aap ek click handler ke andar setA(1) aur setB(2) call karte hain, React setA ke baad immediately re-render nahi karta. Woh dono updates queue karta hai aur ek single re-render schedule karta hai. Aapka component dono naye values apply ke saath ek baar render hota hai.
Har setState call hook ki circular queue mein ek Update object append karta hai. React fiber ko pending work wala mark karta hai aur queue flush karne ke liye ek microtask (ya callback) schedule karta hai â lekin sirf current synchronous code finish hone ke baad.
React 17 mein, batching sirf React event handlers ke andar hoti thi. setTimeout, Promises, ya fetch callbacks ke andar setState calls individual re-renders trigger karti thein. React 18 saare updates automatically batch karta hai, origin se regardless.
Agar aapko ek synchronous DOM update chahiye (jaise state change ke baad layout measure karne ke liye), ReactDOM.flushSync(() => setState(...)) call karein. Yeh React ko update immediately aur synchronously flush karne par force karta hai, batching bypass karta hai.
Jab multiple setState calls previous value par depend karte hain, functional form use karein: setState(prev => prev + 1). React yeh updates queue order mein apply karta hai, toh har update previous wale ka result dekhta hai â render time par value nahi.
React 18 feature: saare setState calls batch hote hain, setTimeout, Promises, aur native event listeners ke andar bhi. Unnecessary re-renders reduce karta hai.
Har hook object par ek circular linked list jo pending setState calls store karti hai. Har batch ke end mein flush hoti hai â saare updates order mein apply hote hain.
React ko pending state updates synchronously aur immediately flush karne par force karta hai. Batching bypass karta hai. Sirf tab use karein jab aapko state change ke baad DOM measurement chahiye.
setState(prev => newValue). Guaranteed latest state value receive karta hai, chahe updates batch ho ya asynchronously enqueue hon.
Batching render count reduce karta hai. Batching ke bina: N setState calls = N renders. Batching ke saath: N setState calls = 1 render.
1// React 18: ALL of these batch into 1 render23// Inside event handler (always batched)4function handleClick() {5 setCount(c => c + 1); // queued6 setFlag(true); // queued7 setName('Alice'); // queued8 // 1 render happens here9}1011// Inside setTimeout â NOW also batched in React 1812setTimeout(() => {13 setCount(c => c + 1); // queued14 setFlag(true); // queued15 // 1 render (React 17 would have triggered 2!)16}, 0);1718// Opt out of batching when needed:19import { flushSync } from 'react-dom';20flushSync(() => setCount(1)); // renders immediately21flushSync(() => setFlag(true)); // renders again22// 2 renders total
Batching React ke sabse important performance optimizations mein se ek hai. Iske bina, ek single user interaction jo 3 state updates trigger karta hai woh 3 full render + reconcile + commit cycles cause karta. Batching ke saath, yeh hamesha sirf 1 hai. React 18 ka automatic batching async code ke liye especially valuable hai â server responses, WebSocket messages, aur timers ab renderer ko thrash nahi karte.
A login form validates email, password, and shows/hides error messages. The submit handler calls `setEmailError(...)`, `setPasswordError(...)`, `setIsSubmitting(false)` â three state updates that should be a single render.
In React 17, calling setState inside setTimeout or fetch().then() didn't batch â each call triggered a separate render. Users would see a flash: first the email error appears, then the password error, then the loading spinner disappears. Three renders for one validation check.
React 18's automatic batching ensures all three setState calls result in ONE render, regardless of whether they're inside an event handler, setTimeout, fetch callback, or promise. The user sees all errors and the stopped spinner simultaneously â no flash.
Takeaway: React 18's automatic batching is a free performance upgrade for existing code. If you migrated from React 17 and had flushSync workarounds for batching, you can now remove them â batching works everywhere automatically.
You need to update a component's state and immediately measure the resulting DOM height to pass to a third-party animation library. With batching, the DOM hasn't updated yet when you try to measure.
Automatic batching defers the DOM update. After calling `setExpanded(true)`, the DOM still shows the collapsed state. Measuring `element.offsetHeight` returns the old height. The animation library receives the wrong value.
Wrap the state update in `flushSync()`: `flushSync(() => setExpanded(true))`. This forces React to immediately commit the DOM update synchronously. The next line can safely measure `element.offsetHeight` and get the expanded height. Use sparingly â it opts out of batching's performance benefit.
Takeaway: flushSync is the escape hatch when you need synchronous DOM access after a state update. Common use cases: third-party animation libraries, scroll position restoration, and focus management. Use it only when batching conflicts with imperative DOM operations.