Labs ICT
Pro Login

Component Lifecycle

What happens when a component mounts, updates, and unmounts.

The Component Lifecycle

Every React component goes through a lifecycle — from birth to death. Understanding this lifecycle is like knowing the stages of a butterfly: it starts as an egg, becomes a caterpillar, transforms into a chrysalis, and finally emerges as a butterfly. Components have similar stages.

The lifecycle has three main phases: mounting (when the component is born), updating (when it grows and changes), and unmounting (when it's removed). React gives you hooks to tap into these moments.

The Mounting Phase

Mounting is when a component is first created and added to the DOM. Think of it as the component's birth moment. This is where you might want to set up initial data, start timers, or make API calls.

In functional components, we use the useEffect hook with an empty dependency array to run code once on mount. It's like telling React, "Hey, when this component first appears, do this for me."

import { useState, useEffect } from "react";

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

  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data));
  }, []);

  if (!user) return <div>Loading...</div>;

  return <h1>{user.name}</h1>;
}
Try it Yourself →

The Updating Phase

Components update when their props or state change. It's like the component growing and adapting to new information. When a user clicks a button, types in an input, or receives new data, the component updates.

The useEffect hook with dependencies runs whenever those dependencies change. It's like setting up a watch: "React, when this value changes, do this for me." You can watch for specific changes and react accordingly.

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}
Try it Yourself →

The Unmounting Phase

Unmounting is when a component is removed from the DOM — its final moment. This is your chance to clean up: cancel timers, unsubscribe from services, or abort API calls. It's like tidying up before you leave a room.

You return a cleanup function from useEffect. React will call this function when the component unmounts. It's like leaving a note: "When I'm gone, do this to clean up after me."

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return <p>{seconds} seconds</p>;
}
Try it Yourself →