useEffect
is a React Hook that lets you perform side effects in functional components.
What are Side Effects?
Side effects are actions that affect things outside of the component's render output. Examples include:
setTimeout
or setInterval
.Why Use useEffect
?
In functional components, you can't directly perform these side effects within the main body of the component. This is because:
useEffect
provides a way to:
How useEffect
Works:
useEffect
takes two arguments:
Basic Usage :
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
// This effect runs after every render
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Dependency Array:
[]
) means the effect will only run once after the initial render.Cleanup Function:
useEffect(() => {
const timerID = setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
clearInterval(timerID); // Cleanup function
};
}, []); // Runs only once
In essence :
useEffect
allows you to synchronize your component with external systems or perform actions that are not directly related to rendering, while also providing a mechanism for cleaning up those actions.