Component Lifecycle
Mounting, updating, unmounting phases, and useEffect equivalents.
Overview
Understanding lifecycle helps manage side effects and resource cleanup.
Key Concepts
- Mounting — Component appears in the DOM
- Updating — State or props change
- Unmounting — Component is removed from DOM
- useEffect — Combines componentDidMount, componentDidUpdate, componentWillUnmount
- useLayoutEffect — Fires synchronously after DOM mutations
Code Examples
function LifecycleDemo({ userId }) {
const [user, setUser] = useState(null);
// componentDidMount + componentDidUpdate(userId)
useEffect(() => {
console.log('Component mounted or userId changed');
fetchUser(userId).then(setUser);
// componentWillUnmount
return () => {
console.log('Cleanup: component will unmount or userId changing');
};
}, [userId]);
// componentDidMount only
useEffect(() => {
console.log('Runs once on mount');
}, []);
// Runs after every render
useEffect(() => {
console.log('Runs on every render');
});
// useLayoutEffect - runs synchronously after DOM updates
useLayoutEffect(() => {
const height = document.body.scrollHeight;
console.log('Layout effect, body height:', height);
});
return <div>{user?.name}</div>;
}
Practice
Convert a class component with lifecycle methods to function components with hooks.