React is one of the most popular JavaScript libraries for building user interfaces. When working with functional components in React, one of the most important hooks you’ll use is useEffect.
What is useEffect?
useEffect is a Hook in React that allows you to handle side effects inside functional components.
What are Side Effects?
Side effects are operations that affect something outside the component. Examples include:
Fetching data from an API
Updating the document title
Setting up timers (setTimeout, setInterval)
Adding event listeners
Subscribing to services
**Basic Synta
x of useEffect**
import { useEffect } from "react";
useEffect(() => {
// Your side effect code here
}, [dependencies]);
First argument -> Function (effect)
Second argument -> Dependency array
When Does useEffect Run?
The behavior of useEffect depends on the dependency array.
1. Run Only Once (On Component Mount)
useEffect(() => {
console.log("Component Mounted");
}, []);
Empty dependency array [] means it runs only once when the component loads.
Example: Fetching data when page loads.
2. Run When a State Changes
useEffect(() => {
console.log("Count changed:", count);
}, [count]);
It runs every time count changes.
Example: Updating document title when count updates.
3. Run On Every Render
useEffect(() => {
console.log("Component Rendered");
});
No dependency array means it runs after every render.
Real-Time Example: Updating Document Title
import { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Click {count}
</button>
);
}
Every time you click the button, the browser tab title updates.
Cleanup Function in useEffect
Sometimes we need to clean up side effects.
**Example: **Removing event listeners or stopping timers.
useEffect(() => {
const timer = setInterval(() => {
console.log("Running...");
}, 1000);
return () => {
clearInterval(timer);
console.log("Cleanup done");
};
}, []);
When does cleanup run?
Before the component unmounts
Before running the effect again (if dependency changes)
Top comments (0)