4.4 React Lifecycle Methods – Understanding Component Lifecycles

Table of Contents

Hey buddy! πŸ‘‹
Ever wondered how a React component is born, lives, and dies? πŸΌπŸ’»πŸ’€

In this article, we’re going to talk about the lifecycle of a React component β€” like how it starts, updates, and cleans up.

Let’s dive in and make it super easy and fun! πŸ„


🎬 What Is a Component Lifecycle?

Think of a React component like a person’s life:

  1. πŸ‘Ά Mounting – it’s born (rendered on the screen).
  2. 🧠 Updating – it changes and grows (when state or props change).
  3. ⚰️ Unmounting – it’s removed from the screen (like retiring).

Each phase gives us a chance to run some code – like calling a friend when you’re born, changing clothes when you grow, or cleaning up your room when you leave.


πŸ› Class Components & Lifecycle Methods

Before Hooks came into React, we used class components to handle lifecycles.

Let’s take a quick peek at a simple class component:

jsxCopyEditimport React from 'react';

class MyComponent extends React.Component {
  componentDidMount() {
    console.log("Component has mounted! 🧱");
  }

  componentDidUpdate() {
    console.log("Component updated! πŸ”");
  }

  componentWillUnmount() {
    console.log("Component will unmount! 🧹");
  }

  render() {
    return <h2>Hello from a Class Component!</h2>;
  }
}

πŸ” What’s Happening Here?

MethodWhen It Runs
componentDidMount()After component appears on screen (once) 🧱
componentDidUpdate()Every time props or state change πŸ”
componentWillUnmount()Right before it disappears 🧹

This is how React lets us manage each stage of a component’s life!


πŸ“¦ Side Effects? What’s That?

Side effects are things your component does outside of returning UI:

  • Fetching data from an API πŸ“‘
  • Subscribing to a service πŸ””
  • Changing the document title πŸ“„
  • Setting up a timer ⏲️

In class components, you’d use lifecycle methods for side effects.
But in modern React (with functional components), we use a hook…


πŸ”§ Meet useEffect – The Lifecycle Hook

useEffect is like a superpower for functional components. πŸ¦Έβ€β™‚οΈ

It runs after the component has rendered β€” just like componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Here’s the basic syntax:

jsxCopyEdituseEffect(() => {
  // Your side effect code here
}, [dependencies]);

πŸ§ͺ Example: Using useEffect to Fetch Data

Let’s fetch user data from an API when the component loads.

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

function UserProfile() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users/1")
      .then(res => res.json())
      .then(data => setUser(data));
  }, []); // empty array means run only once like componentDidMount

  return (
    <div>
      <h2>User Info:</h2>
      {user ? <p>{user.name}</p> : <p>Loading...</p>}
    </div>
  );
}

πŸ“Œ Key Points

  • [] makes it run only once, like componentDidMount.
  • You can put values inside the array to watch for changes.

🧹 Cleaning Up – Like componentWillUnmount

Let’s say you set up a timer or a subscription β€” you should clean it up!

React lets you return a function inside useEffect that runs on unmount.

🧼 Cleanup Example: Timer

jsxCopyEdituseEffect(() => {
  const timer = setInterval(() => {
    console.log("⏰ Tick...");
  }, 1000);

  return () => {
    clearInterval(timer);
    console.log("🧹 Timer cleared!");
  };
}, []);

Now your app won’t have memory leaks!


πŸ“Š React Lifecycle Comparison Table

PhaseClass MethodFunctional HookWhen It Happens
MountcomponentDidMountuseEffect(() => {}, [])After first render
UpdatecomponentDidUpdateuseEffect(() => {}, [value])On dependency change
UnmountcomponentWillUnmountreturn () => {} inside useEffectWhen removed

🧠 Infographic: Lifecycle Flow

1 Fdgc22Mqwbaq7Jofppavig 1
4.4 React Lifecycle Methods – Understanding Component Lifecycles 2

Mount ➑️ Update ➑️ Unmount with Hooks and Class Methods shown side-by-side


🎁 Bonus: Common Side Effects to Use with useEffect

  • πŸ“‘ Fetching data from an API
  • πŸ“œ Subscribing to a WebSocket
  • 🧹 Cleaning up intervals or event listeners
  • πŸ“„ Updating page title or meta tags

🧠 Pro Tips

βœ… Don’t forget the dependency array!
βœ… Cleanup functions avoid memory leaks.
βœ… useEffect can run multiple times, so keep logic tight.


πŸ“š Summary – Lifecycle Made Simple

ConceptMeaning
LifecycleThe different phases a component goes through
componentDidMountRuns after first render (like startup)
useEffectThe modern hook to handle all lifecycle stages
CleanupCode that runs when a component is removed
Side EffectsAnything outside of rendering (like fetching)

πŸ™Œ Keep Learning with Web Codder!

React’s lifecycle gives your app structure and power.
With useEffect, you’re now equipped to manage it like a boss. πŸ’Ό

πŸš€ Want more React tricks and beginner-friendly lessons?

Subscribe and follow:

We’re building smart devs from scratch β€” and you’re one of them! πŸ’‘πŸ‘Š

Share the Post:
Picture of Web Codder

Web Codder

Vikas Sankhla is a seasoned Full Stack Developer with over 7 years of experience in web development. He is the founder of Web Codder, a platform dedicated to providing comprehensive web development tutorials and resources. Vikas specializes in the MERN stack (MongoDB, Express.js, React.js, Node.js) and has been instrumental in mentoring aspiring developers through his online courses and content. His commitment to simplifying complex web technologies has made him a respected figure in the developer community.

Related Posts