When Batching Doesn't Apply
You'll learn: Where React's automatic batching doesn't kick in and you might need to take extra steps.
The Limitation
React's automatic batching works beautifully for code it controls directly—like event handlers (onClick, onChange) and lifecycle methods. But when you step outside React's event system, batching might not happen automatically, especially in pre-React 18 code.
Common Edge Cases
External Event Listeners:
If you attach a native DOM listener directly (using addEventListener), React doesn't wrap that callback. In React 17 and earlier, multiple setState calls inside that listener would trigger separate re-renders:
useEffect(() => {
const handleResize = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight); // Separate render in React 17!
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
Async Code:
Inside setTimeout, promises, or fetch callbacks, React 17 couldn't batch updates because control had left React's hands.
The Solution (React 17 and Earlier)
You could manually batch using ReactDOM.unstable_batchedUpdates:
import { unstable_batchedUpdates } from 'react-dom';
window.addEventListener('resize', () => {
unstable_batchedUpdates(() => {
setWidth(window.innerWidth);
setHeight(window.innerHeight); // Now batched!
});
});
Good news: React 18's automatic batching covers these cases, so this workaround is rarely needed anymore.
Key Takeaway
React's batching works everywhere in React 18+, but in older versions or rare edge cases with external APIs, you might need manual batching helpers to avoid extra renders.