In simple terms, useEffect allows you to run code after a component renders.
Purpose and Usage
useEffect is crucial because functional components are intended to be pure functions (predictable output given the same input).
Operations that interact with the "outside world" need a designated place to run without disrupting the rendering process. Before hooks, these tasks were handled in class components using lifecycle methods.
like componentDidMount, componentDidUpdate, and componentWillUnmount.
Typical uses:
Fetching data from APIs
Updating the DOM
Setting up subscriptions (e.g., WebSocket)
Timers (setTimeout, setInterval)
UseEffect Code
import { useEffect, useState } from "react";
function Count() {
const [count, setCount] = useState(0)
function incre() {
setCount(count + 1)
console.log(count);
}
useEffect(() => {
const interval = setInterval(() => {
console.log("working");
}, 1000);
return (() => {
clearInterval(interval)
})
})
return (
< div >
<h1>{count}</h1>
<button onClick={incre}>+</button>
</div >
)
}
export default Count;
Top comments (0)