React18 Batching Patterns
GitHubOfficialFirst committed by SaravananRajaramanDistributed by GitHub
- Skill
- Guidelines
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
React 18 introduced automatic batching for async operations, which can break legacy class components that rely on immediate re-renders after setState calls. This skill provides a decision framework to categorize these regressions into three types: logic errors caused by reading stale state after await, independent state updates that can be refactored, and scenarios requiring synchronous rendering via flushSync. It emphasizes refactoring over the use of flushSync to maintain React's performance benefits.
What it does
- Provides a diagnostic decision tree for React 18 batching issues.
- Defines three categories of batching regressions (A, B, and C).
- Offers refactoring patterns to replace stale state reads with local variables.
- Explains the correct usage and import syntax for flushSync.
- Identifies anti-patterns where flushSync is misused or unnecessary.
- Helps resolve test failures caused by intermediate state assertions.
When to use it
- When upgrading class components to React 18 and encountering state-related bugs.
- When multiple setState calls in async methods, Promises, or timeouts behave unexpectedly.
- Before implementing flushSync to ensure it is the appropriate solution.
- When fixing test failures that occur after React 18 migration.
Advantages
- Prevents unnecessary performance degradation caused by overusing flushSync.
- Provides clear, actionable refactoring patterns for common bugs.
- Reduces silent state-read bugs by promoting better async state management.
- Helps maintain the performance benefits of React 18 concurrent rendering.
Usage examples
- “How do I fix a bug where my class component reads this.state after an await and gets the old value?”
- The skill guides you to Category A, advising you to remove the conditional state read and use local variables or restructure the logic to avoid relying on intermediate state.
- “When is it appropriate to use flushSync in a React 18 class component?”
- The skill explains that flushSync should only be used when the user must see an intermediate UI state, such as a loading spinner, before an async operation begins.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/github/react18-batching-patterns/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip react18-batching-patterns.zip -d .agents/skills
Documentation by SaravananRajaraman
React 18 Automatic Batching Patterns
Reference for diagnosing and fixing the most dangerous silent breaking change in React 18 for class-component codebases.
The Core Change
| Location of setState | React 17 | React 18 |
|---|---|---|
| React event handler | Batched | Batched (same) |
| setTimeout | Immediate re-render | Batched |
| Promise .then() / .catch() | Immediate re-render | Batched |
| async/await | Immediate re-render | Batched |
| Native addEventListener callback | Immediate re-render | Batched |
Batched means: all setState calls within that execution context flush together in a single re-render at the end. No intermediate renders occur.
Quick Diagnosis
Read every async class method. Ask: does any code after an await read this.state to make a decision?
Code reads this.state after await?
YES → Category A (silent state-read bug)
NO, but intermediate render must be visible to user?
YES → Category C (flushSync needed)
NO → Category B (refactor, no flushSync)For the full pattern for each category, read:
references/batching-categories.md- Category A, B, C with full before/after codereferences/flushSync-guide.md- when to use flushSync, when NOT to, import syntax
The flushSync Rule
Use flushSync sparingly. It forces a synchronous re-render, bypassing React 18's concurrent scheduler. Overusing it negates the performance benefits of React 18.
Only use flushSync when:
The user must see an intermediate UI state before an async operation begins
A spinner/loading state must render before a fetch starts
Sequential UI steps have distinct visible states (progress wizard, multi-step flow)
In most cases, the fix is a refactor - restructuring the code to not read this.state after await. Read references/batching-categories.md for the correct approach per category.
Files
- ATTRIBUTION.mdAdded by AutoGineer903 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md2.4 KiB
- references/batching-categories.md5.8 KiB
- references/flushSync-guide.md2.4 KiB
references/batching-categories.md
Batching Categories - Before/After Patterns
Category A - this.state Read After Await (Silent Bug) {#category-a}
The method reads this.state after an await to make a conditional decision. In React 18, the intermediate setState hasn't flushed yet - this.state still holds the pre-update value.
Before (broken in React 18):
async handleLoadClick() {
this.setState({ loading: true }); // batched - not flushed yet
const data = await fetchData();
if (this.state.loading) { // ← still FALSE (old value)
this.setState({ data, loading: false }); // ← never called
}
}After - remove the this.state read entirely:
async handleLoadClick() {
this.setState({ loading: true });
try {
const data = await fetchData();
this.setState({ data, loading: false }); // always called - no condition needed
} catch (err) {
this.setState({ error: err, loading: false });
}
}Pattern: If the condition on this.state was always going to be true at that point (you just set it to true), remove the condition. The setState you called before await will eventually flush - you don't need to check it.
Category A Variant - Multi-Step Conditional Chain
// Before (broken):
async initialize() {
this.setState({ step: 'auth' });
const token = await authenticate();
if (this.state.step === 'auth') { // ← wrong: still initial value
this.setState({ step: 'loading', token });
const data = await loadData(token);
if (this.state.step === 'loading') { // ← wrong again
this.setState({ step: 'ready', data });
}
}
}// After - use local variables, not this.state, to track flow:
async initialize() {
this.setState({ step: 'auth' });
try {
const token = await authenticate();
this.setState({ step: 'loading', token });
const data = await loadData(token);
this.setState({ step: 'ready', data });
} catch (err) {
this.setState({ step: 'error', error: err });
}
}Category B - Independent setState Calls (Refactor, No flushSync) {#category-b}
Multiple setState calls in a Promise chain where order matters but no intermediate state reading occurs. The calls just need to be restructured.
Before:
handleSubmit() {
this.setState({ submitting: true });
submitForm(this.state.formData)
.then(result => {
this.setState({ result });
this.setState({ submitting: false }); // two setState in .then()
});
}After - consolidate setState calls:
async handleSubmit() {
this.setState({ submitting: true, result: null, error: null });
try {
const result = await submitForm(this.state.formData);
this.setState({ result, submitting: false });
} catch (err) {
this.setState({ error: err, submitting: false });
}
}Rule: Multiple setState calls in the same async context already batch in React 18. Consolidating into fewer calls is cleaner but not strictly required.
Category C - Intermediate Render Must Be Visible (flushSync) {#category-c}
The user must see an intermediate UI state (loading spinner, progress step) BEFORE an async operation starts. This is the only case where flushSync is the right answer.
Diagnostic question: "If the loading spinner didn't appear until after the fetch returned, would the UX be wrong?"
YES →
flushSyncNO → refactor (Category A or B)
Before:
async processOrder() {
this.setState({ status: 'validating' }); // user must see this
await validateOrder(this.props.order);
this.setState({ status: 'charging' }); // user must see this
await chargeCard(this.props.card);
this.setState({ status: 'complete' });
}After - flushSync for each required intermediate render:
import { flushSync } from 'react-dom';
async processOrder() {
flushSync(() => {
this.setState({ status: 'validating' }); // renders immediately
});
await validateOrder(this.props.order);
flushSync(() => {
this.setState({ status: 'charging' }); // renders immediately
});
await chargeCard(this.props.card);
this.setState({ status: 'complete' }); // last - no flushSync needed
}Simple loading spinner case (most common):
import { flushSync } from 'react-dom';
async handleSearch() {
// User must see spinner before the fetch begins
flushSync(() => this.setState({ loading: true }));
const results = await searchAPI(this.state.query);
this.setState({ results, loading: false });
}setTimeout Pattern
// Before (React 17 - setTimeout fired immediate re-renders):
handleAutoSave() {
setTimeout(() => {
this.setState({ saving: true });
// React 17: re-render happened here
saveToServer(this.state.formData).then(() => {
this.setState({ saving: false, lastSaved: Date.now() });
});
}, 2000);
}// After (React 18 - all setState inside setTimeout batches):
handleAutoSave() {
setTimeout(async () => {
// If loading state must show before fetch - flushSync
flushSync(() => this.setState({ saving: true }));
await saveToServer(this.state.formData);
this.setState({ saving: false, lastSaved: Date.now() });
}, 2000);
}Test Patterns That Break Due to Batching
// Before (React 17 - intermediate state was synchronously visible):
it('shows saving indicator', () => {
render(<AutoSaveForm />);
fireEvent.change(input, { target: { value: 'new text' } });
expect(screen.getByText('Saving...')).toBeInTheDocument(); // ← sync check
});
// After (React 18 - use waitFor for intermediate states):
it('shows saving indicator', async () => {
render(<AutoSaveForm />);
fireEvent.change(input, { target: { value: 'new text' } });
await waitFor(() => expect(screen.getByText('Saving...')).toBeInTheDocument());
await waitFor(() => expect(screen.getByText('Saved')).toBeInTheDocument());
});Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
SaravananRajaraman
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/react18-batching-patterns · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- SaravananRajaraman
AutoGineer is not affiliated with or endorsed by SaravananRajaraman or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download react18-batching-patterns.zip