Lifecycle
The series of phases that a React component goes through from creation (mounting) to removal (unmounting), with opportunities to run code at specific points.
Overview
Every React component has a lifecycle with three main phases: mounting (insertion into DOM), updating (re-rendering), and unmounting (removal from DOM). In class components, lifecycle methods provide hooks into these phases. In function components, the useEffect hook covers most lifecycle scenarios.
Example
javascript// Class component lifecycle class MyComponent extends React.Component { componentDidMount() { // Runs after component is added to DOM console.log('Component mounted'); } componentDidUpdate(prevProps, prevState) { // Runs after component updates if (this.props.userId !== prevProps.userId) { this.fetchUser(this.props.userId); } } componentWillUnmount() { // Cleanup before component is removed console.log('Component will unmount'); } render() { return <div>{this.props.children}</div>; } } // Function component equivalent with hooks function MyComponent({ userId }) { useEffect(() => { console.log('Component mounted'); return () => { console.log('Component will unmount'); }; }, []); useEffect(() => { fetchUser(userId); }, [userId]); return <div>Content</div>; }
Key Points
- Three phases: mount, update, unmount
- Class components: use lifecycle methods
- Function components: use useEffect hook
- Mounting: component added to DOM
- Unmounting: component removed from DOM
Learn More
- useEffect - Effect hook
- Component - React components
- Hooks - React Hooks
- React Docs: Lifecycle