Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
useEffect is a hook in React that allows performing side effects in functional components. Side effects can include operations such as server requests, event subscriptions, DOM manipulations and much more.
useEffect executes after component renders. It allows you to perform actions that shouldn't block rendering, such as asynchronous requests or updates that should occur after render.
useEffect(() => {
// Side effect code
}, [dependencies]);
import { useState, useEffect } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
// Start timer when component mounts
useEffect(() => {
const intervalId = setInterval(() => {
setSeconds((prevSeconds) => prevSeconds + 1);
}, 1000);
// Clean up effect when component unmounts
return () => clearInterval(intervalId);
}, []); // Empty array — effect will execute only once
return (
<div>
<p>Time elapsed: {seconds} seconds</p>
</div>
);
}
import { useState, useEffect } from "react";
function FetchData() {
const [data, setData] = useState(null);
const [url, setUrl] = useState("https://api.example.com/data");
useEffect(() => {
const fetchData = async () => {
const response = await fetch(url);
const result = await response.json();
setData(result);
};
fetchData();
}, [url]); // Hook will fire when `url` changes
return (
<div>
<button onClick={() => setUrl("https://api.example.com/new-data")}>
Load new data
</button>
<p>{data ? JSON.stringify(data) : "Loading..."}</p>
</div>
);
}
If hook requires cleanup (e.g., when working with subscriptions or timers), you can return function from useEffect:
useEffect(() => {
const intervalId = setInterval(() => {
console.log("Timer working...");
}, 1000);
return () => clearInterval(intervalId); // Clear timer
}, []);
Using useEffect:
useEffect allows handling side effects in functional components, improving state and resource management in React applications.