Middle
Tell about batching in React. Where have you encountered it in practice?
sobes.tech AI
Answer from AI
In React, batching is the process of combining multiple state or prop updates into a single render to improve performance and avoid unnecessary re-renders.
Previously, React automatically batched updates only within event handlers. Starting with React 18, batching also works in asynchronous operations, such as promises or setTimeout.
Example of batching:
function Component() {
const [count, setCount] = React.useState(0);
const [text, setText] = React.useState('');
function handleClick() {
setCount(c => c + 1);
setText('updated');
// React will combine these two updates into one render
}
return <button onClick={handleClick}>{count} - {text}</button>;
}
In practice, I encountered batching when optimizing performance, especially when trying to avoid multiple renders during sequential state updates.