React18 Lifecycle 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
This skill provides a systematic decision-making framework for migrating unsafe React class component lifecycle methods (componentWillMount, componentWillReceiveProps, and componentWillUpdate) to modern, React 18-compliant alternatives. It emphasizes identifying the semantic purpose of legacy code—whether it involves state initialization, side effects, or prop-based state derivation—to ensure the correct migration pattern is applied. The skill explicitly warns against using the UNSAFE_ prefix as a permanent solution and provides clear before-and-after code examples for various migration scenarios.
What it does
- Routes legacy lifecycle methods to correct modern replacements based on semantic intent.
- Provides specific migration patterns for state initialization, side effects, and prop derivation.
- Offers guidance on handling asynchronous work and cleanup in componentDidUpdate.
- Explains the risks of using UNSAFE_ prefixes and provides a template for temporary code marking.
- Includes decision trees for choosing between getDerivedStateFromProps and componentDidUpdate.
- Demonstrates how to implement getSnapshotBeforeUpdate for DOM-related lifecycle tasks.
When to use it
- When refactoring class components to resolve React 18.3.1 lifecycle warnings.
- When preparing a codebase for future React 19 compatibility.
- When deciding between getDerivedStateFromProps and componentDidUpdate for prop-driven logic.
- When needing to safely move side effects out of deprecated lifecycle methods.
- When implementing DOM-read operations that require getSnapshotBeforeUpdate.
Advantages
- Prevents common migration errors by enforcing a semantic decision-making process.
- Ensures compatibility with React 18 concurrent mode by eliminating unsafe lifecycle usage.
- Provides clear, copy-pasteable code patterns for complex refactoring tasks.
- Reduces technical debt by discouraging the use of temporary UNSAFE_ prefixes.
Usage examples
- “How do I migrate a componentWillMount that fetches data?”
- The skill directs you to Case B in the componentWillMount reference, advising you to move the fetch logic into componentDidMount and handle cleanup in componentWillUnmount.
- “Should I use getDerivedStateFromProps for my API call?”
- The skill warns against this, explaining that getDerivedStateFromProps is for pure state derivation only, and guides you to use componentDidUpdate for asynchronous side effects.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/github/react18-lifecycle-patterns/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip react18-lifecycle-patterns.zip -d .agents/skills
Documentation by SaravananRajaraman
React 18 Lifecycle Patterns
Reference for migrating the three unsafe class component lifecycle methods to React 18.3.1 compliant patterns.
Quick Decision Guide
Before migrating any lifecycle method, identify the semantic category of what the method does. Wrong category = wrong migration. The table below routes you to the correct reference file.
componentWillMount - what does it do?
| What it does | Correct migration | Reference |
|---|---|---|
Sets initial state (this.setState(...)) | Move to constructor | → componentWillMount.md |
| Runs a side effect (fetch, subscription, DOM) | Move to componentDidMount | → componentWillMount.md |
| Derives initial state from props | Move to constructor with props | → componentWillMount.md |
componentWillReceiveProps - what does it do?
| What it does | Correct migration | Reference |
|---|---|---|
| Async side effect triggered by prop change (fetch, cancel) | componentDidUpdate | → componentWillReceiveProps.md |
| Pure state derivation from new props (no side effects) | getDerivedStateFromProps | → componentWillReceiveProps.md |
componentWillUpdate - what does it do?
| What it does | Correct migration | Reference |
|---|---|---|
| Reads the DOM before update (scroll, size, position) | getSnapshotBeforeUpdate | → componentWillUpdate.md |
| Cancels requests / runs effects before update | componentDidUpdate with prev comparison | → componentWillUpdate.md |
The UNSAFE_ Prefix Rule
Never use UNSAFE_componentWillMount, UNSAFE_componentWillReceiveProps, or UNSAFE_componentWillUpdate as a permanent fix.
Prefixing suppresses the React 18.3.1 warning but does NOT:
Fix concurrent mode safety issues
Prepare the codebase for React 19 (where these are removed, with or without the prefix)
Fix the underlying semantic problem the migration is meant to address
The UNSAFE_ prefix is only appropriate as a temporary hold while scheduling the real migration sprint. Mark any UNSAFE_ prefix additions with:
// TODO: React 19 will remove this. Migrate before React 19 upgrade.
// UNSAFE_ prefix added temporarily - replace with componentDidMount / getDerivedStateFromProps / etc.Reference Files
Read the full reference file for the lifecycle method you are migrating:
references/componentWillMount.md- 3 cases with full before/after codereferences/componentWillReceiveProps.md- getDerivedStateFromProps trap warnings, full examplesreferences/componentWillUpdate.md- getSnapshotBeforeUpdate + componentDidUpdate pairing
Read the relevant file before writing any migration code.
Files
- ATTRIBUTION.mdAdded by AutoGineer905 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md3.6 KiB
- references/componentWillMount.md3.7 KiB
- references/componentWillReceiveProps.md5.0 KiB
- references/componentWillUpdate.md4.7 KiB
references/componentWillReceiveProps.md
componentWillReceiveProps Migration Reference
The Core Decision
Does componentWillReceiveProps trigger async work or side effects?
YES → componentDidUpdate
NO (pure state derivation only) → getDerivedStateFromPropsWhen 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.
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-lifecycle-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-lifecycle-patterns.zip