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/componentWillUpdate.md
componentWillUpdate Migration Reference
The Core Decision
Does componentWillUpdate read the DOM (scroll, size, position, selection)?
YES → getSnapshotBeforeUpdate (paired with componentDidUpdate)
NO (side effects, request cancellation, etc.) → componentDidUpdateCase A - Reads DOM Before Re-render {#case-a}
The method captures a DOM measurement (scroll position, element size, cursor position) before React applies the next update, so it can be restored or adjusted after.
Before:
class MessageList extends React.Component {
componentWillUpdate(nextProps) {
if (nextProps.messages.length > this.props.messages.length) {
this.savedScrollHeight = this.listRef.current.scrollHeight;
this.savedScrollTop = this.listRef.current.scrollTop;
}
}
componentDidUpdate(prevProps) {
if (prevProps.messages.length < this.props.messages.length) {
const scrollDelta = this.listRef.current.scrollHeight - this.savedScrollHeight;
this.listRef.current.scrollTop = this.savedScrollTop + scrollDelta;
}
}
}After - getSnapshotBeforeUpdate + componentDidUpdate:
class MessageList extends React.Component {
// Called right before DOM updates are applied - perfect timing to read DOM
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevProps.messages.length < this.props.messages.length) {
return {
scrollHeight: this.listRef.current.scrollHeight,
scrollTop: this.listRef.current.scrollTop,
};
}
return null; // Return null when snapshot is not needed
}
// Receives the snapshot as the third argument
componentDidUpdate(prevProps, prevState, snapshot) {
if (snapshot !== null) {
const scrollDelta = this.listRef.current.scrollHeight - snapshot.scrollHeight;
this.listRef.current.scrollTop = snapshot.scrollTop + scrollDelta;
}
}
}Why this is better than componentWillUpdate: In React 18 concurrent mode, there can be a gap between when componentWillUpdate runs and when the DOM actually updates. DOM reads in componentWillUpdate may be stale. getSnapshotBeforeUpdate runs synchronously right before the DOM is committed - the reads are always accurate.
The contract:
Return a value from
getSnapshotBeforeUpdate→ that value becomessnapshotincomponentDidUpdateReturn
null→snapshotincomponentDidUpdateisnullAlways check
if (snapshot !== null)incomponentDidUpdategetSnapshotBeforeUpdateMUST be paired withcomponentDidUpdate
Case B - Side Effects Before Update {#case-b}
The method cancels an in-flight request, clears a timer, or runs some preparatory side effect when props or state are about to change.
Before:
class SearchResults extends React.Component {
componentWillUpdate(nextProps) {
if (nextProps.query !== this.props.query) {
this.currentRequest?.cancel();
this.setState({ loading: true, results: [] });
}
}
}After - move to componentDidUpdate (run AFTER the update):
class SearchResults extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.query !== this.props.query) {
// Cancel the stale request
this.currentRequest?.cancel();
// Start the new request for the updated query
this.setState({ loading: true, results: [] });
this.currentRequest = searchAPI(this.props.query)
.then(results => this.setState({ results, loading: false }));
}
}
}Note: The side effect now runs AFTER the render, not before. In most cases this is correct - you want to react to the state that's actually showing, not the state that was showing. If you truly need to run something synchronously BEFORE a render, reconsider the design - that usually indicates state that should be managed differently.
Both Cases in One Component
If a component had both DOM-reading AND side effects in componentWillUpdate:
// Before: does both
componentWillUpdate(nextProps) {
// DOM read
if (isExpanding(nextProps)) {
this.savedHeight = this.ref.current.offsetHeight;
}
// Side effect
if (nextProps.query !== this.props.query) {
this.request?.cancel();
}
}After: split into both patterns:
// DOM read → getSnapshotBeforeUpdate
getSnapshotBeforeUpdate(prevProps, prevState) {
if (isExpanding(this.props)) {
return { height: this.ref.current.offsetHeight };
}
return null;
}
// Side effect → componentDidUpdate
componentDidUpdate(prevProps, prevState, snapshot) {
// Handle snapshot if present
if (snapshot !== null) { /* ... */ }
// Handle side effect
if (prevProps.query !== this.props.query) {
this.request?.cancel();
this.startNewRequest();
}
}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