Index of every page on this site: llms.txt
All skills
github avatar

/react18-lifecycle-patterns

@f10fdb8 official
by githubgithub/awesome-copilot42k stars
5,426
Run it yourself

Provides exact before/after migration patterns for the three unsafe class component lifecycle methods - componentWillMount, componentWillReceiveProps, and componentWillUpdate - targeting React 18.3.1. Use this skill whenever a class component needs its lifecycle methods migrated, when deciding between getDerivedStateFromProps vs componentDidUpdate, when adding getSnapshotBeforeUpdate, or when fixing React 18 UNSAFE_ lifecycle warnings. Always use this skill before writing any lifecycle migration code - do not guess the pattern from memory, the decision trees here prevent the most common migration mistakes.

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

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencescomponentWillReceiveProps.md

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

componentWillReceiveProps Migration Reference

The Core Decision

Does componentWillReceiveProps trigger async work or side effects?
  YES → componentDidUpdate
  NO (pure state derivation only) → getDerivedStateFromProps

When in doubt: use componentDidUpdate. It's always safe. getDerivedStateFromProps has traps (see bottom of this file) that make it the wrong choice when the logic is anything other than purely synchronous state derivation.


Case A - Async Side Effects / Fetch on Prop Change {#case-a}

The method fetches data, cancels requests, updates external state, or runs any async operation when a prop changes.

Before:

class UserProfile extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.userId !== this.props.userId) {
      this.setState({ loading: true, profile: null });
      fetchProfile(nextProps.userId)
        .then(profile => this.setState({ profile, loading: false }))
        .catch(err => this.setState({ error: err, loading: false }));
    }
  }
}

After - componentDidUpdate:

class UserProfile extends React.Component {
  componentDidUpdate(prevProps) {
    if (prevProps.userId !== this.props.userId) {
      // Use this.props (not nextProps - the update already happened)
      this.setState({ loading: true, profile: null });
      fetchProfile(this.props.userId)
        .then(profile => this.setState({ profile, loading: false }))
        .catch(err => this.setState({ error: err, loading: false }));
    }
  }
}

Key difference: componentDidUpdate receives prevProps - you compare prevProps.x !== this.props.x instead of this.props.x !== nextProps.x. The update has already applied.

Cancellation pattern (important for async):

class UserProfile extends React.Component {
  _requestId = 0;

  componentDidUpdate(prevProps) {
    if (prevProps.userId !== this.props.userId) {
      const requestId = ++this._requestId;
      this.setState({ loading: true });
      fetchProfile(this.props.userId).then(profile => {
        // Ignore stale responses if userId changed again
        if (requestId === this._requestId) {
          this.setState({ profile, loading: false });
        }
      });
    }
  }
}

Case B - Pure State Derivation from Props {#case-b}

The method only derives state values from the new props synchronously. No async work, no side effects, no external calls.

Before:

class SortedList extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.items !== this.props.items) {
      this.setState({
        sortedItems: [...nextProps.items].sort((a, b) => a.name.localeCompare(b.name)),
      });
    }
  }
}

After - getDerivedStateFromProps:

class SortedList extends React.Component {
  // Must track previous prop to detect changes
  static getDerivedStateFromProps(props, state) {
    if (props.items !== state.prevItems) {
      return {
        sortedItems: [...props.items].sort((a, b) => a.name.localeCompare(b.name)),
        prevItems: props.items, // ← always store the prop you're comparing
      };
    }
    return null; // null = no state change
  }

  constructor(props) {
    super(props);
    this.state = {
      sortedItems: [...props.items].sort((a, b) => a.name.localeCompare(b.name)),
      prevItems: props.items, // ← initialize in constructor too
    };
  }
}

getDerivedStateFromProps - Traps and Warnings

Trap 1: It fires on EVERY render, not just prop changes

Unlike componentWillReceiveProps, getDerivedStateFromProps is called before every render - including setState calls. Always compare against previous values stored in state.

// WRONG - fires on every render, including setState triggers
static getDerivedStateFromProps(props, state) {
  return { sortedItems: sort(props.items) }; // re-sorts on every setState!
}

// CORRECT - only updates when items reference changes
static getDerivedStateFromProps(props, state) {
  if (props.items !== state.prevItems) {
    return { sortedItems: sort(props.items), prevItems: props.items };
  }
  return null;
}

Trap 2: It cannot access this

getDerivedStateFromProps is a static method. No this.props, no this.state, no instance methods.

// WRONG - no this in static method
static getDerivedStateFromProps(props, state) {
  return { value: this.computeValue(props) }; // ReferenceError
}

// CORRECT - pure function of props + state
static getDerivedStateFromProps(props, state) {
  return { value: computeValue(props) }; // standalone function
}

Trap 3: Don't use it for side effects

If you need to fetch when a prop changes - use componentDidUpdate. getDerivedStateFromProps must be pure.

When getDerivedStateFromProps is actually the wrong tool

If you find yourself doing complex logic in getDerivedStateFromProps, consider whether the consuming component should receive pre-processed data as a prop instead. The pattern exists for narrow use cases, not general prop-to-state syncing.

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo4 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill provides safe documentation and code examples for migrating React lifecycle methods. No security issues were detected.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

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

Last checked against GitHub 4 days ago.

Activeupdated 7 months ago
  • React
  • react18
  • lifecycle
  • class-components
  • migration
  • componentwillmount
  • componentwillreceiveprops
  • componentwillupdate
  • getderivedstatefromprops
  • getsnapshotbeforeupdate

README badge

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

Provides decision trees and before/after code patterns for migrating React class component lifecycle methods (componentWillMount, componentWillReceiveProps, componentWillUpdate) to React 18.3.1 compliant equivalents. Targets the three unsafe lifecycle methods specifically and routes each to the correct replacement (constructor, componentDidMount, getDerivedStateFromProps, getSnapshotBeforeUpdate, or componentDidUpdate) based on whether the code performs side effects or derives state.

Generated from the current SKILL.md.

Does this skill cover all three unsafe lifecycle methods?
Yes. It provides migration patterns for componentWillMount, componentWillReceiveProps, and componentWillUpdate, with decision trees to route each to the correct replacement (constructor, componentDidMount, getDerivedStateFromProps, getSnapshotBeforeUpdate, or componentDidUpdate).
Can I just add the UNSAFE_ prefix to suppress warnings?
No. The skill explicitly warns that UNSAFE_ prefixes suppress warnings but do not fix concurrent mode safety issues or prepare code for React 19, where these methods are removed entirely. Real migration is required.
How do I know which migration pattern to use?
The skill provides a semantic decision guide—you identify what the lifecycle method does (e.g. sets initial state, runs async side effects, reads the DOM) and the table routes you to the correct replacement and reference file.
Does this target a specific React version?
Yes, React 18.3.1. The patterns account for concurrent mode and React 18 specific behavior.

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