useEffect
React useEffect hook performs side effect in react. useEffect is called only after the component rendered. This is one of the most important concepts in React.
Nothing to worry if you don't have an idea what are the things that are considered as side effects in React. This is used when we need to fetch an API to use the data(Network calls) or when we require cleanup.
Now let's have a look at general syntax of the useEffect.
useEffect(() => {
console.log("useEffect works fine");
})
The above code works fine. The useEffect is called once the component is rendered. It is also called whenever there is any change in state/props of component and then it updates the effects.
We can restrict calling the useEffect for every single change in the component. This can be done by passing second argument as an array in the useEffect.
useEffect (() => {
console.log("called only once")
}, [])
In the above code the useEffect is passed by an empty array which is known as dependency array. This helps to run the useEffect only once after the component is rendered. Further, any changes in state/props of the component will not affect the useEffect.
This useEffect can be executed conditionally after implementing the dependency array too. This can be done by passing the values in the dependency array.
useEffect(() => {
console.log("works conditionally");
} ,[count])
In the above code, the useEffect is called with a dependency array which holds a value i.e., count. Whenever the value of count changes, the useEffect is executed.
We can also pass multiple values in this dependency array. If there is a change in any single value passed, then useEffect is executed.
useEffect(() => {
console.log("value changed in array");
}, [ count, age ])
Multiple useEffect :
It's fine to use multiple useEffect in a single functional component. Using multiple useEffect will not throw any error. By using "useEffect for multiple times", the code becomes more readable and can implement multiple effects.
Clean-up function :
Once the effects are created in the component, they need to be cleaned up before the component is removed from the DOM. This clean-up function can be done by using return function in useEffect.
useEffect(() => {
// effect
...
// clean-up function
return () => {}
}
The below code shows the working of clean-up function :
import { useEffect, useState } from "react";
function Cleanup() {
const [counter, setCounter] = useState(5000);
useEffect(() => {
setTimeout(() => {
setCounter((prevCounter) => prevCounter - 1);
console.log(counter);
}, 1500);
}, [counter]);
return (
<div>
<p>{counter}</p>
</div>
);
};
If we execute the code, it works well. But, it gives a warning when we try to remove this component from DOM and move it to another component.
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
If we need to overcome this error, we need to implement a clean-up function i.e., return function in useEffect hook.
Here, setTimeout() method calls a function at regular time intervals. Before the component is removed from the DOM, it has to be cleared by clean-up function. So, clearTimeout() method is called in the return function.
useEffect(() => {
const setTimeoutVar = setTimeout(() => {
setCounter((prevCounter) => prevCounter - 1);
console.log(counter);
}, 1500);
return () => clearTimeout(setTimeoutVar);
}, [counter]);