🧠 Understanding useEffect
in React (The Easy Way)
In React, when you want to do something after the page is shown, like:
- Fetch data from a server
- Update the title of the tab
- Set a timer
- Listen for a keypress or window event
You use useEffect
! It's a React Hook made just for this.
✅ Basic Format
useEffect(() => {
// do something here
return () => {
// optional: cleanup
};
}, [dependencies]);
📌 Example 1: Run Once When Page Loads
import { useEffect } from 'react';
function Hello() {
useEffect(() => {
console.log('Page loaded!');
}, []); // runs only once
return <h1>Hello!</h1>;
}
This effect runs only once when the component is shown the first time.
🔄 Example 2: Run When a Value Changes
function Welcome({ name }) {
useEffect(() => {
console.log('Name changed to:', name);
}, [name]);
return <h2>Welcome, {name}!</h2>;
}
It runs every time the name
prop changes.
🧹 Example 3: Cleanup (Like Clearing a Timer)
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
clearInterval(timer);
console.log('Timer cleared');
};
}, []);
The function inside return
runs when the component is removed or re-rendered.
🌐 Example 4: Fetching Data from an API
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
This will run once on page load and fetch user data.
🧪 Example 5: Changing Page Title
import { useEffect } from "react";
function TitleChanger({ count }) {
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return <p>Count is: {count}</p>;
}
The page title changes every time count
changes.
📊 Summary Table
What You Want to Do | How to Use |
---|---|
Run once when the component shows | useEffect(..., []) |
Run when a value changes | useEffect(..., [value]) |
Do cleanup when unmounting | return () => { /* clean */ } |
Run on every render | useEffect(...) // no array |
💡 Final Tips
- Put only what’s needed in the dependency array
- Cleanup things like timers or event listeners
- You can use multiple
useEffect
hooks for different tasks
That’s it! With practice, useEffect
becomes your best friend for connecting React with the outside world 🌍.
Have questions? Drop them in the comments or try building a small app using useEffect
now!
0 Comments