β±οΈ React useEffect() Hook
useEffect()
is a React Hook that lets you perform side effects like fetching data, setting up event listeners, or updating the DOM directly.
π¦ Basic Usage
import React, { useEffect, useState } from 'react';
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Component mounted or updated');
});
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
}
By default, useEffect runs after every render. You can control this behavior using the dependency array.
π useEffect with Dependency Array
useEffect(() => {
console.log('Runs only once on mount');
}, []);
- []
makes the effect run only once (like componentDidMount
)
- Add values inside the array to re-run when they change
π Fetching Data
useEffect(() => {
async function fetchData() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
console.log(data);
}
fetchData();
}, []);
You canβt make the useEffect()
callback async directly β define an async function inside it.
π§Ή Cleanup Function
useEffect(() => {
const interval = setInterval(() => {
console.log('Running every second...');
}, 1000);
return () => clearInterval(interval); // Cleanup
}, []);
Cleanup functions prevent memory leaks by clearing timers, subscriptions, or event listeners when a component unmounts.
β Summary
useEffect()
lets you run code after rendering- It replaces lifecycle methods like
componentDidMount
,componentDidUpdate
,componentWillUnmount
- Always handle cleanup for subscriptions/timers
- Use the dependency array to control execution