React automatic batching
Created By: chatGPT
In React 18, automatic batching of state updates was introduced. This means that multiple state updates inside an event handler or within any other callback will automatically be batched together. Prior to this, batching only happened during React events, which could lead to performance issues and unnecessary re-renders.
function Counter() {
const [count, setCount] = React.useState(0);
const updateCount = () => {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={updateCount}>Increase Count</button>
</div>
);
}
With automatic batching, you can update the state without encouraging unnecessary re-renders. This makes it particularly useful when you need to make multiple updates based on a series of events, such as clicks or other interactions.
function App() {
const [data, setData] = React.useState(null);
const fetchData = async () => {
const user = await getUserApi();
const posts = await getPostsApi();
setData({ user, posts }); // Both state updates will be batched together
};
return (
<div>
<button onClick={fetchData}>Fetch Data</button>
{data && <DisplayData data={data} />}
</div>
);
}
In cases where you might use async functions or promises, automatic batching can still apply. This allows for cleaner and more efficient code. If you're using libraries like Redux, ensure that your state management logic also supports this feature to take full advantage.
const handleFetch = async () => {
const user = await fetchUser();
const settings = await fetchSettings();
// React will batch these updates automatically
setUser(user);
setSettings(settings);
};
Key Takeaway: Automatic batching simplifies your React applications by allowing you to group state updates, reducing the number of renders and improving performance. Always aim to keep your state updates encapsulated within batchable updates, especially during user interactions, to harness these performance benefits fully.
function SubmitForm() {
const [name, setName] = React.useState('');
const [email, setEmail] = React.useState('');
const handleSubmit = () => {
// Batch updates for form submission
setName('');
setEmail('');
};
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={e => setName(e.target.value)} />
<input value={email} onChange={e => setEmail(e.target.value)} />
<button type='submit'>Submit</button>
</form>
);
}