Component Lifecycle
The component lifecycle is the sequence of phases a React component goes through: mounting (appearing on screen), updating (re-rendering when data changes), and unmounting (being removed). The useEffect Hook lets you run code at these moments.
React
Every component has a life: it mounts when first added to the page, updates whenever its state or props change, and unmounts when removed. Older class components used named methods like componentDidMount for these phases.
In modern function components, you express lifecycle behavior with useEffect. An effect with an empty dependency array runs once on mount; listing dependencies makes it run on relevant updates; and the function you return from an effect runs on unmount as cleanup, perfect for clearing timers or subscriptions.
Examples
JSX — Logs 'mounted' when the component first appears and 'unmounted' when it is removed from the page.
import { useEffect } from "react";
function Timer() {
useEffect(() => {
console.log("mounted");
return () => console.log("unmounted");
}, []);
return <p>Running...</p>;
}Output:
mounted