What is useEffect
?
useEffect
is a React hook that lets you perform side effects in your components.
Side effects are things like:
- Fetching data from an API
- Updating the DOM manually
- Setting up a timer
- Logging data
It runs after the component renders.
syntax useEffect
Basic Syntax
useEffect(() => {
// code to run (side effect)
});
- Runs after every render by default.
Run only once (on mount)
useEffect(() => {
// code to run once
}, []);
- Empty dependency array
[]
→ runs only when component mounts.
Run on specific state or prop change
useEffect(() => {
// code to run when `variable` changes
}, [variable]);
-
variable
→ dependency, runs only when this changes.
Cleanup function (optional)
useEffect(() => {
// setup code
return () => {
// cleanup code (like unsubscribing, clearing timers)
};
}, [dependencies]);
When to use useEffect
- When you want something to happen after render.
- When you want to watch for changes in a variable (state or props).
- When you want to clean up resources (like timers, subscriptions) when a component unmounts.
Where to use
- Inside a functional component.
Simple Code Example
import React, { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
// useEffect runs after every render by default
useEffect(() => {
console.log("Count changed:", count);
}, [count]); // dependency array
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
export default Counter;
Explanation:
-
useEffect(() => {...}, [count])
→ Runs only whencount
changes. - Without
[count]
, it runs after every render. - With
[]
(empty array), it runs only once when the component mounts.
Top comments (0)