All skills
github avatar

/react18-batching-patterns

@90921cc official
by githubgithub/awesome-copilot40k stars
5,040

Provides exact patterns for diagnosing and fixing automatic batching regressions in React 18 class components. Use this skill whenever a class component has multiple setState calls in an async method, inside setTimeout, inside a Promise .then() or .catch(), or in a native event handler. Use it before writing any flushSync call - the decision tree here prevents unnecessary flushSync overuse. Also use this skill when fixing test failures caused by intermediate state assertions that break after React 18 upgrade.

Use this Skill: https://skilld.dev/gh/github/awesome-copilot/react18-batching-patterns

This session only. Nothing lands on disk.

referencesbatching-categories.md

≈1.5k tokens on demand. Your agent reads this file only when SKILL.md points to it.

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 → flushSync
  • NO → 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());
});

Source: SKILL.md on GitHub

No alerts15d4 checks · Risk SAFE
  • Gen Agent Trust Hub15d

    This skill provides technical documentation and code patterns for diagnosing and fixing React 18 automatic batching regressions. It is purely informational and contains no executable code or external dependencies.

  • Socket15d

    No alerts

  • Snyk15d

    Risk: LOW · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 90921cc. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 5 months ago

README badge

README badge for github/awesome-copilot/react18-batching-patterns

Provides decision trees and patterns for diagnosing and fixing React 18's automatic batching behavior in class components, particularly setState calls in async methods, Promises, and native event handlers that silently broke in React 18. Use this before adding flushSync calls to determine whether you need synchronous re-renders or should refactor to avoid reading stale state after await.

Generated from the current SKILL.md.

Does this skill apply to functional components with hooks?
No. This skill targets class components only. React 18 batching behavior for functional components with useState is different and not covered here.
When should I use flushSync to fix a batching regression?
Only when the user must see an intermediate UI state before an async operation begins, like a loading spinner before a fetch. Most batching regressions should be fixed by refactoring to avoid reading this.state after await, not by adding flushSync.
Does this skill help with test failures after upgrading to React 18?
Yes. It covers fixing test failures caused by intermediate state assertions that break after React 18 upgrade, since intermediate re-renders no longer occur in setTimeout, Promise .then(), or async/await contexts.
What async contexts are affected by React 18 batching changes?
setTimeout, Promise .then()/.catch(), async/await, and native addEventListener callbacks now batch setState calls together in React 18, whereas React 17 would re-render immediately after each one.

Generated from the current SKILL.md. These answers refresh after source changes.