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:
- Seeding (Mounting) π±
- Growing (Updating) πΏ
- 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>;
}
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>
);
}
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>;
}
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._
Top comments (0)