DEV Community

Cover image for React component lifecycle . . .
_Khojiakbar_
_Khojiakbar_

Posted on

React component lifecycle . . .

Imagine a Little Plant 🌱

Think of a React component as a little plant. This plant goes through different stages of its life, just like your component does. The stages are:

  1. Seeding (Mounting) 🌱
  2. Growing (Updating) 🌿
  3. Wilting (Unmounting) πŸ‚

Stage 1: Seeding (Mounting) 🌱

When you plant a seed, it starts to grow roots and leaves. In React, this is when a component is created and put into the DOM (the web page).

  • useEffect(() => {...}, []): This is when the plant has sprouted and is fully in the garden. This hook runs after the component has been added to the DOM. It’s a great place to fetch data from an API or set up timers.
import React, { useEffect } from 'react';

function Plant() {
  useEffect(() => {
    console.log('Plant has sprouted!');
  }, []);

  return <div>🌱</div>;
}
Enter fullscreen mode Exit fullscreen mode

Stage 2: Growing (Updating) 🌿

Now, our little plant is growing. It gets taller, maybe grows some flowers. In React, this is when a component updates because it received new props or its state changed.

  • useEffect(() => {...}, [state]): This is like checking if the plant has grown since the last time you looked at it. This hook runs after the component has updated.
import React, { useState, useEffect } from 'react';

function Plant() {
  const [size, setSize] = useState('small');

  useEffect(() => {
    console.log('Plant has sprouted!');
  }, []);

  useEffect(() => {
    console.log(`Plant grew to ${size}!`);
  }, [size]);

  const grow = () => {
    setSize('large');
  };

  return (
    <div>
      🌿
      <button onClick={grow}>Grow</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Stage 3: Wilting (Unmounting) πŸ‚

Every plant eventually wilts and dies. In React, this is when a component is removed from the DOM.

  • useEffect(() => {... return () => {...} }, []): This is like when you remove the wilted plant from the garden. You might clean up any mess it left, like taking away the pot or turning off the watering system. The cleanup function runs when the component is removed.
import React, { useEffect } from 'react';

function Plant() {
  useEffect(() => {
    console.log('Plant has sprouted!');

    return () => {
      console.log('Plant is wilting away...');
    };
  }, []);

  return <div>πŸ‚</div>;
}
Enter fullscreen mode Exit fullscreen mode

Why is the Lifecycle Important?

Understanding the lifecycle helps you know when to do certain things in your component, like:

  • _Fetching data when the component is first added to the page (useEffect with an empty dependency array []).

  • Performing actions when the component updates (useEffect with dependencies [state]).

  • Cleaning up resources (like removing event listeners or canceling network requests) when the component is removed (cleanup function inside useEffect).

By following these stages, you ensure your component behaves correctly and efficiently throughout its life on the web page._

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay