React 18 Batching: What's Changed and How to Optimize

React Batching = 1 render. Before React 18 (React 17 & earlier) React only auto-batched state updates inside React event handlers (like onClick, onChange). Multiple setState calls in the same handler = 1 re-render so that is great for these usages. But on the other hand => (setTimeout / setInterval , Promise.then / async await,addEventListener and useEffect callbacks somtimes) React doesn't patching all in one render and Each setState triggered a separate re-render and the result be unnecessary renders that cause wasted CPU and laggy lists, forms, loaders, modals, etc. Started from React 18 everything has changed with (createRoot) 1-Automatic batching now happens almost everywhere! 2-All updates in the same event loop / microtask get grouped once for single re-render. Examples: // Click handler (always batched, even before) const handleClick = () => { setCount(c => c + 1); setLoading(true); // 1 render (same as before) }; // Async fetch – previously 2 renders, now 1! const handleFetch = async () => { const data = await fetchData(); setData(data); setLoading(false); // 1 render in React 18 }; // setTimeout – previously 2 renders, now 1! setTimeout(() => { setCount(c => c + 1); setFlag(true); }, 0); // 1 render that is okay but what if we have a case that need to separate the renders then we need to use flushSync from 'react-dom' and wrap the state with it to ensure separated renders. Example: flushSync(() => { setCount(c => c + 1); }); Hope it was helpful! #React #React18 #JavaScript #Frontend #WebDev #Performance #ReactJS #FrontendDevelopment

  • diagram

To view or add a comment, sign in

Explore content categories