What does useEffect() do?
What useEffect() does
The useEffect() hook lets you run side effects in a functional component.
A "side effect" is anything that goes beyond a plain JSX render:
- server requests,
- working with
localStorage,- subscriptions and timers,
- changing
document.title,- interacting with the DOM.
Syntax
javascript
useEffect(() => {
// side effect
return () => {
// optional cleanup
};
}, [dependencies]);- The first argument is a function (the effect) that runs after the render.
- The second argument is a dependency array, which controls when the effect runs.
- The function returned from the effect is the cleanup, run before the component is removed or before the effect runs again.
Example - an API request
javascript
import { useEffect, useState } from "react";
function User() {
const [user, setUser] = useState(null);
useEffect(() => {
fetch("/api/user")
.then(res => res.json())
.then(setUser);
}, []); // empty array -> the effect runs once
return <div>{user ? user.name : "Loading..."}</div>;
}Here useEffect makes the request once, when the component mounts.
(the same as componentDidMount() in classes)
How the dependency array works
| Dependency array | When the effect runs |
|---|---|
[] | Once, on mount |
[someValue] | On the first render and whenever someValue changes |
| no array | On every render |
Example:
javascript
useEffect(() => {
console.log("count changed");
}, [count]);Runs on the first render and every time count changes.
Cleaning up an effect
If an effect creates something that needs to be canceled or released (for example, a timer or a subscription), you can return a cleanup function:
javascript
useEffect(() => {
const timer = setInterval(() => console.log("tick"), 1000);
return () => {
clearInterval(timer); // clean up on unmount
};
}, []);This is the equivalent of componentWillUnmount() in class components.
Example - changing the page title
javascript
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);Every time count changes, document.title is updated.
Important to remember
| Rule | Explanation |
|---|---|
useEffect always runs after the render | Does not block the UI |
| The dependency array is required | Without it, the effect runs on every render |
| Returning a function is the effect's cleanup | Used to unsubscribe or release resources |
useEffect cannot be called inside conditions or loops | Only at the top level of the component |
Summary
| Question | Answer |
|---|---|
What does useEffect() do | Lets you run side effects (requests, timers, subscriptions, DOM operations) |
| When does it run | After the render, depending on dependencies |
| What does the returned function do | Cleans up the effect (for example, unsubscribes or stops timers) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.