DEV Community

Shivam Sharma
Shivam Sharma

Posted on

Life of a React Component: From Baby to Retirement 👶➡️👨‍💻➡️🏖️

Hey folks!
This is my first-ever article, so feel free to judge me—constructively, of course—so I can improve next time (just kidding... or maybe not 🤔).

Okay, let’s dive in:
What comes to your mind when you hear the word "Lifecycle"?
Everyone will imagine different kinds of scenarios. For example: Some might think about the human lifecycle—how a child is born, grows up, learns new things from others, becomes independent, and eventually, retires (from life... just kidding, but hey, it’s kind of true!).

Guess what? That’s exactly how React’s Lifecycle works.
I’m going to break it down step by step, just like life.

  1. Birth (Mounting):
    When the React component is created and added to the DOM, think of it like a baby taking its first breath.

  2. Growth (Updating):
    Just like we grow, learn, and evolve, React components also update and change over time, based on new information (state or props).

  3. Retirement (Unmounting):
    And finally, when a component’s job is done, it gracefully says goodbye and is removed from the DOM. 👋

In React terms, these are the Mounting, Updating, and Unmounting phases of the lifecycle. Simple, right? (Okay, maybe not yet, but stay with me!)

Now, let’s break it down in more detail:

  1. Birth Phase (Mounting):

This is where the magic begins—the baby React component comes into existence! When a component is mounted, React goes through the following steps:

constructor(): This is like the “hello world” moment for your component. It’s born and initializes its state and props.
render(): React says, “Alright, show me what you got!” and runs the render() method to display the UI.

componentDidMount(): Once everything is ready and visible on the screen, this method runs. It’s the perfect place to fetch data, set up subscriptions, or initialize animations.
Example:



class BabyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isHappy: true };
    console.log("Baby is born!");
  }

  componentDidMount() {
    console.log("Baby has learned to walk!");
  }

  render() {
    return <div>I'm a happy baby! 😊</div>;
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Growth Phase (Updating): Now our baby is growing up! The component updates when:

The state changes (e.g., the baby gets a toy).
The props change (e.g., the baby’s parent gives it a cookie 🍪).
Here’s what happens:

shouldComponentUpdate(): React asks, “Do I really need to update, or can I chill?” This is where you can optimize performance by controlling unnecessary updates.
render(): If updates are necessary, React calls render() again to refresh the UI.
componentDidUpdate(): React says, “Update complete! Let’s clean up or do something cool now.”
Example:




class TeenagerComponent extends React.Component {
  state = { mood: "happy" };

  shouldComponentUpdate(nextProps, nextState) {
    console.log("Should I update? 🤔");
    return nextState.mood !== this.state.mood; // Update only if the mood changes
  }

  componentDidUpdate() {
    console.log("Updated! Teenager got moody again.");
  }

  render() {
    return <div>Mood: {this.state.mood}</div>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Think of it like a teenager who changes moods often—React needs to figure out when it’s worth refreshing the UI.

  1. Goodbye Phase (Unmounting): Every journey has an end, and so does a React component’s life. When it’s time to say goodbye, React runs:

componentWillUnmount(): This is where you clean up—close subscriptions, clear timers, or say goodbye to anything the component was managing.
Example:


class RetiredComponent extends React.Component {
  componentWillUnmount() {
    console.log("Time to retire. Cleaning up!");
  }

  render() {
    return <div>Goodbye, world! 👋</div>;
  }
}

Enter fullscreen mode Exit fullscreen mode

Modern Twist: React Hooks and useEffect
If you’re working with functional components (as you should in modern React), the lifecycle is a bit different. Everything revolves around useEffect.

How useEffect Works:
useEffect is like the Swiss Army knife of React lifecycles—it can handle mounting, updating, and unmounting all in one place.

Example:



import React, { useState, useEffect } from "react";

function FunctionalComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component mounted or updated!");

    return () => {
      console.log("Component unmounted or cleanup happens here.");
    };
  }, [count]); // Only runs when 'count' changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, useEffect handles all three lifecycle phases. You can perform side effects on mount, update, or unmount all within a single hook. It’s a cleaner and more powerful way to handle side effects in functional components.

Key Takeaways:
The React lifecycle has three phases: Mounting, Updating, and Unmounting.
Class components use lifecycle methods like componentDidMount and componentWillUnmount.
Functional components use useEffect to manage all lifecycle-related tasks.
Always clean up resources in the unmounting phase to avoid memory leaks.

Final Thoughts:

I hope you all understand this, and if not—don’t worry! You’ll get it with good practice and consistency. Many people don’t understand this at first, and I was one of them. So, no need to stress!

Also, feel free to drop your feedback so I can improve next time. 😊

Top comments (2)

Collapse
 
sanjana_das_fcc4f79fb4989 profile image
Sanjana Das

Nice one🥳

Collapse
 
shivamsharmxa profile image
Shivam Sharma

Thanks