The useEffect hook lets you perform side effects in functional components — like fetching data, updating the DOM, or setting up timers.
📌 Basic Example:
import { useEffect, useState } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Click {count}
</button>
);
}
✨ Key Points:
• Runs after render
• Add dependencies in [] → decides when effect runs
• Return a cleanup function to avoid memory leaks
👉 Example Cleanup:
useEffect(() => {
const timer = setInterval(() => console.log("Running..."), 1000);
return () => clearInterval(timer); // cleanup
}, []);
React’s useEffect keeps your UI and side effects in sync! 🚀
Top comments (0)