Component Lifecycle
Component Lifecycle
Every React component goes through a lifecycle of three main phases: Mounting, Updating, and Unmounting.
Understanding these phases is crucial for knowing when to fetch data, set up subscriptions, or clean up resources.
1. Mounting (Birth)
Mounting is the phase when a component is created and inserted into the DOM for the very first time.
What happens:
- React calls the component function.
- React takes the returned JSX and constructs the initial DOM nodes.
- The browser paints the screen.
- If there are any
useEffecthooks, React runs them after the paint.
In old Class Components, this phase was associated with the componentDidMount lifecycle method.
2. Updating (Growth)
A component updates whenever there is a change to its state or its props.
What happens:
- React calls the component function again with the new state/props.
- React compares the new JSX output with the previous output (Reconciliation).
- React applies only the necessary changes to the actual DOM.
- The browser repaints the updated parts of the screen.
- React cleans up the previous
useEffect(if dependencies changed) and runs the newuseEffect.
In old Class Components, this phase was associated with the componentDidUpdate lifecycle method.
3. Unmounting (Death)
Unmounting is the phase when a component is removed from the DOM. This happens when the component is no longer rendered by its parent (e.g., hiding it via conditional rendering, or navigating to a new page).
What happens:
- React calls the cleanup functions returned by any active
useEffecthooks. - React removes the component’s nodes from the DOM.
- The component and its state are destroyed and garbage collected.
In old Class Components, this phase was associated with the componentWillUnmount lifecycle method.
The Mental Shift with Hooks
While it is helpful to understand the Mount/Update/Unmount paradigm, React Hooks (specifically useEffect) encourage a different mental model. Instead of thinking about “lifecycle events”, you should think about synchronization.
An Effect synchronizes your component with an external system. It “starts synchronizing” when the component mounts, “re-synchronizes” when dependencies change during updates, and “stops synchronizing” when it unmounts.
Interview Questions
Q: What are the three main phases of a React component’s lifecycle?
A:
- Mounting: The component is created and inserted into the DOM.
- Updating: The component is re-rendered due to changes in state, props, or context.
- Unmounting: The component is permanently removed from the DOM.