React Automatic Batching: How Many Re-renders?
Source: Dev.to
Example
import { useState } from 'react';
const App = () => {
const [name, setName] = useState('');
const [age, setAge] = useState(null);
const [hobby, setHobby] = useState('');
const displayPerson = () => {
setName('Luiji');
setAge(29);
setHobby('swimming');
};
console.log('Component rendered');
return (
<>
### {name}
### {age}
#### Enjoys: {hobby}
{name === 'Yoshi' ? 'Display Person' : 'Person Displayed'}
);
};
export default App;
When you click the button, the component re‑renders once, not three times. This is because React automatically batches the state updates that occur within the same event loop.
Note: The first
console.logruns on the initial render; the second runs after the button click triggers the re‑render.
What is Batching?
Batching groups multiple state updates into a single render pass, reducing unnecessary work and improving performance. In React 18, automatic batching is enabled by default and works for:
- Native event handlers (e.g., clicks)
- Asynchronous operations (e.g., promises)
- Timeouts and intervals
Because all three setState calls (setName, setAge, setHobby) happen during the same click event, React batches them and performs only one render.