Sitemap
Ritzz

Ritzz

FULL STACK DEVELOPER

React Life Cycle

4 min readOct 16, 2024

--

React life cycle is similar to human life cycle.
The lifecycle is a series of methods that are invoked at different stages of a component’s existence.

Press enter or click to view image in full size
Press enter or click to view image in full size

The React Component Lifecycle Phases:

1)Mounting (Birth): When a component is created and added to the DOM.

constructor(): Initializes the component’s state and props.

render(): Responsible for rendering the JSX to the DOM.

componentDidMount(): Invoked right after the component is mounted in the DOM. Ideal for starting side-effects like API calls.

2)Updating (Growth): When the component’s state or props are updated and the component re-renders.

shouldComponentUpdate(): Determines if the component should re-render when there are state or prop changes.

render(): Re-renders the component.

getSnapshotBeforeUpdate(): Captures the state of the DOM before the update, often used for preserving scroll position.

componentDidUpdate(): Invoked after the component has updated, used to run side-effects after updates.

3)Unmounting (Death): When the component is removed from the DOM.

componentWillUnmount(): Clean-up method, used to remove timers, cancel API calls, or remove event listeners before the component is destroyed.

Get Ritzz’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s understand it via code

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

Here’s a breakdown of your ClassLifeCycle1 component:

1. Constructor (constructor)

  • The constructor initializes the component's state with:
  • fruit set to "Cherry"
  • count set to 0
  • This state is used for rendering the component and updating the UI.
constructor() {
super();
this.state = {
fruit: "Cherry",
count: 0,
};
}

2. getDerivedStateFromProps (Static Lifecycle Method)

  • This method is called every time the component receives new props, before rendering.
  • It logs the incoming props and updates the fruit value in the state to match the prop value.
  • Note: Since this method is static, it does not have access to this, but it can return a new state object.
static getDerivedStateFromProps(props, state) {
console.log(props);
return { fruit: props.fruit }; // Updates state with new props
}

3. componentDidMount

  • This lifecycle method is called after the component is initially rendered (mounted) to the DOM.
  • Here, it logs a message indicating the component has mounted.
componentDidMount() {
console.log("componentDidMount()");
}

4. shouldComponentUpdate

  • This method controls whether the component should re-render on state/prop changes.
  • It logs a message each time an update is about to occur.
  • Currently, it always returns true, meaning the component will always re-render when the state/props change.
shouldComponentUpdate() {
console.log("Component Update");
return true; // Always allows updates
}

5. getSnapshotBeforeUpdate

  • This method is used to capture some information (snapshot) before the DOM is updated.
  • In your case, it logs the previous state (prevState) but returns null since no snapshot is needed.
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("Prev State", prevState);
return null; // No snapshot is needed
}

6. componentDidUpdate

  • This method is called after the component has updated (re-rendered).
  • It logs the snapshot (which is null in this case) and logs that the component has updated.
  • It checks if the count has reached 5. If it has, it logs a message that the component will unmount and resets the count back to 0.
componentDidUpdate(prevProps, prevState, snapshot) {
console.log(snapshot);
console.log("componentDidUpdate()");
  if (this.state.count === 5) {
console.log("Component will unmount now!");
this.setState({ count: 0 }); // Reset count to simulate unmount
}
}

7. componentWillUnmount

  • This method is called just before the component is unmounted from the DOM.
  • It shows an alert notifying that the component has been unmounted.
componentWillUnmount() {
alert("Unmounted");
}

8. render

  • This method returns the JSX that defines the UI of the component.
  • It renders the fruit and count from the state, along with a button to update the count.
  • The button increases the count by 1 each time it's clicked.
render() {
console.log("Render()");
  return (
<div>
<h1>React life Cycle in Class Based Component</h1>
<h2>Fruit : {this.state.fruit}</h2>
<h2>Count : {this.state.count}</h2>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Update Count
</button>
</div>
);
}

Key Lifecycle Flow:

Mounting:

  • constructor → getDerivedStateFromProps → render → componentDidMount

Updating:

  • getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshotBeforeUpdate → componentDidUpdate

Unmounting:

  • componentWillUnmount

Behavior:

  • The count increases by 1 every time the button is clicked.
  • When count reaches 5, a message is logged ("Component will unmount now!") and the count is reset to 0, simulating the unmounting process.
  • If the component is unmounted, an alert pops up saying “Unmounted”.

--

--

Written by Ritzz

0 followers

FULL STACK DEVELOPER