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 कैसे परफॉर्मेंस के लिए कई setState calls को एक री-रेंडर में बदलता है।
State batching का अर्थ है React same synchronous block से कई setState calls collect करता है और उन सभी को एक single re-render pass में process करता है। हर individual setState के बाद re-render करने के बजाय, React current 'batch' के अंत तक प्रतीक्षा करता है, सभी updates एक साथ apply करता है, और exactly एक बार render करता है। React 18 ने async code और native event listeners को भी cover करने के लिए automatic batching extend किया।
जब आप click handler के अंदर setA(1) और setB(2) call करते हैं, React setA के बाद immediately re-render नहीं करता। यह दोनों updates queue करता है और एक single re-render schedule करता है। आपका component एक बार दोनों नई values के साथ render होता है।
प्रत्येक setState call hook की circular queue में एक Update object append करता है। React fiber को pending work के रूप में mark करता है और queue flush करने के लिए microtask (या callback) schedule करता है — लेकिन current synchronous code finish होने के बाद ही।
React 17 में, batching केवल React event handlers के अंदर होती थी। setTimeout, Promises, या fetch callbacks के अंदर setState calls individual re-renders trigger करती थीं। React 18 सभी updates को automatically batch करता है, origin चाहे जो हो।
यदि आपको synchronous DOM update चाहिए (जैसे state change के बाद layout measure करना), ReactDOM.flushSync(() => setState(...)) call करें। यह React को update immediately और synchronously flush करने के लिए force करता है, batching को bypass करते हुए।
जब कई setState calls previous value पर depend करती हैं, functional form उपयोग करें: setState(prev => prev + 1)। React इन updates को queue order में apply करता है, इसलिए प्रत्येक update render time की value नहीं बल्कि पिछले update का result देखता है।
React 18 feature: सभी setState calls batch होती हैं, setTimeout, Promises, और native event listeners के अंदर भी। Unnecessary re-renders कम करता है।
प्रत्येक hook object पर एक circular linked list जो pending setState calls store करती है। प्रत्येक batch के अंत में flush होती है — सभी updates order में apply होते हैं।
React को pending state updates synchronously और immediately flush करने के लिए force करता है। Batching bypass करता है। केवल तब उपयोग करें जब state change के बाद DOM measurement की ज़रूरत हो।
setState(prev => newValue)। Latest state value प्राप्त करने की guarantee, तब भी जब updates batch या asynchronously enqueue हों।
Batching render count कम करता है। Batching के बिना: N setState calls = N renders। Batching के साथ: 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 के सबसे important performance optimizations में से एक है। इसके बिना, एक single user interaction जो 3 state updates trigger करती है, 3 full render + reconcile + commit cycles का कारण बनती। Batching के साथ, यह हमेशा सिर्फ 1 होता है। React 18 का automatic batching async code के लिए विशेष रूप से valuable है — server responses, WebSocket messages, और timers अब renderer को thrash नहीं करते।
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.