What is useEffect?
useEffect is a React Hook used to perform side effects in a component. A side effect is an operation that happens outside the normal React rendering process. Some common examples are using setInterval, adding an event listener, fetching data from an API, or changing the browser document title.
The basic syntax of useEffect is:
useEffect(() => {
// side effect code
}, []);
The second parameter is called the dependency array. An empty array means the effect runs after the component is initially rendered.
For example, we can use useEffect to change the browser title:
import { useEffect, useState } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
Here, whenever count changes, the component renders again and the useEffect runs because count is included in the dependency array.
useEffect with setInterval and Event Listener
useEffect is useful with setInterval because an interval keeps running until we stop it. We can create the interval inside useEffect and use the cleanup function to stop it.
useEffect(() => {
const timer = setInterval(() => {
console.log("Hello");
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
The setInterval runs every one second. When the component is removed, the cleanup function runs and clearInterval() stops the timer.
The same idea can be used with an event listener.
useEffect(() => {
function handleKeyDown(event) {
console.log(event.key);
}
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, []);
Here, the event listener waits for the user to press a keyboard key. When a key is pressed, handleKeyDown runs and prints the key in the console.
The cleanup function removes the event listener when the component is no longer needed.
Without useEffect, an event listener could be added again every time the component re-renders. This can cause unnecessary or duplicate listeners. useEffect helps us control when the listener is added and the cleanup function helps us remove it.
So the general pattern is:
useEffect(() => {
// start or add something
return () => {
// stop or remove something
};
}, []);
For example, setInterval() can be cleaned with clearInterval(), and addEventListener() can be cleaned with removeEventListener().
In simple terms, useEffect is used when we need React to perform an operation after rendering and when necessary clean up that operation later.
Top comments (0)