React components go through a series of lifecycle phases when rendered and updated. Here's a breakdown of the key stages:
1. Mounting (挂载)
- ComponentDidMount: Executes after the component is rendered to the DOM.
💡 Use this for side effects like data fetching or DOM manipulation.
2. Updating (更新)
- ComponentDidUpdate: Runs when props or state change.
⚠️ Ensure to avoid infinite loops by comparingprevProps
andprevState
.
3. Unmounting (卸载)
- ComponentWillUnmount: Called before the component is removed from the DOM.
💡 Clean up subscriptions or timers here.
4. Newer React (React 16+)
- useEffect Hook: Replaces most lifecycle methods in functional components.
🔄 UseuseEffect
for side effects with dependency arrays to control when it runs.
For a visual guide, check out our React Lifecycle Diagram. Want to dive deeper into hooks? Explore React Hooks Essentials.