useEffectis a React Hook that lets you perform side effects in functional components.- Side effects are actions outside React’s rendering process, like:
- Fetching data from an API
- Updating the DOM directly
- Setting up subscriptions (e.g., WebSocket, Event Listener)
- Starting/clearing timers
👉 In class components, we used lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount).
👉 In functional components, all of these are handled inside useEffect().
🔹 Syntax
useEffect(() => {
// side effect logic here
return () => {
// cleanup logic here (optional)
};
}, [dependencies]);
🔹 How It Works?
- 1st argument → A function containing side effect code.
- 2nd argument (dependency array) → Controls when the effect runs.
🔹 Cases of Dependency Array
- No dependency array → Runs after every render.
useEffect(() => {
console.log("Runs after every render");
});
- Empty dependency array
[]→ Runs only once (likecomponentDidMount).
useEffect(() => {
console.log("Runs only once when component mounts");
}, []);
- With dependencies
[var]→ Runs only when that variable changes.
useEffect(() => {
console.log("Runs when count changes");
}, [count]);
- Cleanup Function → Runs before component unmounts or before next effect runs.
useEffect(() => {
const interval = setInterval(() => {
console.log("Interval running");
}, 1000);
return () => clearInterval(interval); // cleanup
}, []);
🔹 Example: Fetching Data with useEffect
import React, { useState, useEffect } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
async function fetchData() {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await res.json();
setUsers(data);
}
fetchData();
}, []); // runs only once
return (
<div>
<h2>Users List</h2>
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
</div>
);
}
export default Users;
🔹 Key Points for Interviews
useEffectreplaces lifecycle methods in functional components.- The dependency array controls when effect runs.
- Always clean up subscriptions, event listeners, or intervals inside the
returncleanup function. - Without dependencies → runs on every render → can cause infinite loops if not handled carefully.
✅ Short Interview Answer
“
useEffectis a hook that allows us to perform side effects in functional components, like data fetching, subscriptions, or timers. It takes a function and a dependency array. If dependencies are empty, it runs only once; if dependencies change, it re-runs. It can also return a cleanup function for resource management.”