Component Lifecycle
The component lifecycle is the set of distinct phases a UI component passes through from the moment it is created and added to the DOM to the moment it is removed — and the hooks developers can use to run code at each transition.
The component lifecycle is the set of distinct phases a UI component passes through from the moment it is created and added to the DOM to the moment it is removed — and the hooks developers can use to run code at each transition.
All major JavaScript frameworks — React, Vue, Angular, Svelte — expose a lifecycle model, though the naming varies. React hooks like useEffect and useLayoutEffect map onto these phases. Vue exposes onMounted, onUpdated, onBeforeUnmount. Angular uses ngOnInit, ngOnChanges, ngOnDestroy. Despite the naming differences, the underlying phase model is consistent.
Mounting is the initial phase where the component is instantiated, its initial state and props are set, and it renders for the first time into the DOM. During mounting, the constructor (or setup() in Vue) runs, then the render function, then the framework attaches the output to the real DOM. After the DOM is available, componentDidMount / onMounted / useEffect with an empty dependency array fires. This is the correct place to start data fetches, subscribe to event emitters, or initialize third-party libraries that need a DOM node.
Updating happens whenever the component's state or incoming props change. The render function re-runs, the framework performs reconciliation (see Virtual DOM Diffing), and after the DOM is updated, componentDidUpdate / onUpdated fires. React's useEffect dependencies list controls which updates trigger a given effect.
Unmounting occurs when the component is removed from the component tree — for example, when the user navigates away or a condition renders it out. componentWillUnmount / onBeforeUnmount fires here and is the correct place to cancel timers, unsubscribe from observables, remove event listeners, and clean up any resources to prevent memory leaks. In React, useEffect cleanup functions run at this phase and also before each re-run of the effect.
Understanding the lifecycle is essential for writing side-effect-free, leak-free components and for correctly timing data fetches and subscriptions.