Like useState which we have discussed in a previous blog useEffect is another react hook which makes functional react development easier for us. The useEffect handles side effects caused by mounting, unmounting, updating & changing states in react dom. The useEffect takes a callback function which is executed after the above-mentioned changes in react dom.
For those who are familiar with class based react development useEffect works as alternative for componenetDidUpdate, componentDidMount, componentDidUnmount, etc.
In order to use useEffect we must have to import it in react.
import { useEffect } from "react";
syntax-
useEffect(callback_function, dependency_array)
Here dependency array is an optional parameter.
Let's understand how to use basic implementation of useEffect by simple example below
As shown in the above example we have given a function inside useEffect which will run when any of the dom change happens. In the above example, we are changing the state of a counter upon clicking the button. So, every time when the state is changing react-dom gets re-rendered & function inside useEffect is running.
Now, as we can see in the above example function inside useEffect gets triggered when any of the states is changing. If we want to run the effect only when the particular state or states changes then this is also possible using the dependency array as the second parameter to useEffect.
As shown in the above example here the function inside useEffect gets triggered only when state of counter1 changes. This is due to the dependency array which we have used as the second argument to useEffect. As the dependency is in array format we can also specify multiple state values as dependancies.
So, now we can handle sideEffects for particular state changes. But, what about effects which we only want to run once when the dom is mounted initially. E.g. in some cases of API's we only need to call the once when our dom is mounted. This can also be handled by using an empty dependency array.
As shown in the above code here code inside useEffect is running only once when the dom gets mounted. Code inside useEffect is not getting triggered on any of the state changes as we have used an empty array as a dependency here.
End Notes: Hope you like the blog. If you have any suggestions please feel free to comment. Happy Coding! Good Day!