
ReactJS
useEffect lets you perform side effects in functional components. It handles API calls, timers, subscriptions, and other effects that need to run after render.
useEffect takes a function that runs after render. You can optionally provide a dependency array to control when the effect runs.
The effect runs after every render by default. Adding a dependency array controls when it runs. An empty array means it runs once after initial render.
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Runs after every render
useEffect(() => {
document.title = `Count: ${count}`;
});
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}The dependency array controls when effects run. Leave it out for every render, empty array for once, or add specific values to run when they change.
import { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
const [id, setId] = useState(1);
// Runs only on mount (empty array)
useEffect(() => {
console.log('Component mounted');
}, []);
// Runs when id changes
useEffect(() => {
fetch(`/api/data/${id}`)
.then(r => r.json())
.then(setData);
}, [id]);
return (
<div>
<p>Data: {data}</p>
<button onClick={() => setId(id + 1)}>Next</button>
</div>
);
}| Dependency | Behavior |
|---|---|
| None | Runs after every render |
| `[]` | Runs once after mount |
| `[value]` | Runs when value changes |
Ready to practice? Challenges
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward