How do hooks affect component lifecycle?
In class components, the lifecycle is managed using methods like componentDidMount,
componentDidUpdate, and componentWillUnmount. With hooks, these are replaced
with useEffect, which can mimic any lifecycle behavior.
Lifecycle Mapping:
- componentDidMount: Use useEffect with an empty dependency array ([]).
- componentDidUpdate: Use useEffect with dependencies.
- componentWillUnmount: Return a cleanup function inside useEffect.
Example:
useEffect(() => {
// Equivalent to componentDidMount and componentDidUpdate
console.log("Component mounted or updated");
return () => {
// Equivalent to componentWillUnmount
console.log("Cleanup before component unmount");
};
}, [dependencies]); // Will run on mount and update based on
dependencies