Lifecycle
In one line
Lifecycle refers to the sequence of phases a component goes through: mounting (added to DOM), updating (state/props change), and unmounting (removed from DOM).
In simple words
Every React component goes through a lifecycle: it is mounted (created and added to the DOM), updated (re-rendered when state or props change), and unmounted (removed from the DOM).
In class components, lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount let you run code at each phase. In function components, the useEffect Hook covers all of them: the setup function runs on mount and updates, and the returned cleanup function runs on unmount and before each re-effect.
Understanding the lifecycle is crucial for side effects: fetch data on mount, subscribe on mount and unsubscribe on unmount, clean up timers on unmount. Forgetting cleanup leads to memory leaks and stale state updates.
Example
useEffect(() => {
// Mount + update: subscribe
const sub = api.subscribe(handler);
return () => {
// Unmount / before next effect: unsubscribe
sub.unsubscribe();
};
}, []); // [] = run only on mount, cleanup on unmountThe effect subscribes on mount. The cleanup function unsubscribes when the component unmounts, preventing memory leaks.
Related terms
Related Resources
Related Lessons
- Component Lifecycle
Learn mount, update, and unmount phases.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.