React Component Lifecycle
Component Lifecycle
The component lifecycle in React describes the stages a React component goes through from creation to removal in the browser. You can think of it like the life of a person:
- Born (Mounting) — the component is created & inserted into the DOM.
- Grows / Changes (Updating) — whenever it receives new props or its state changes, it updates.
- Dies (Unmounting) — it gets removed from the DOM, and cleanup happens.
The 3 main phases:
1. Mounting
This is when the component first gets created & rendered on the screen. In class components:
- constructor
- render
- componentDidMount
2. Updating
Whenever props or state change, the component re-renders. In class components:
- render
- componentDidUpdate
3. Unmounting
When the component is removed from the screen / DOM. In class components:
- componentWillUnmount
Example:
What happens when?
Mounting (first time component appears on screen):
- constructor ➡️ render ➡️ componentDidMount
Updating (after setState or new props):
- render ➡️ componentDidUpdate
Unmounting (component removed from DOM):
- componentWillUnmount
functional components (with hooks)
The useEffect hook is used to handle side-effects during mounting, updating, and unmounting.