useEffect is very useful in React Hooks. UseEffect React lifecycle work to control effects in your components like Data Fetching, Updateting DOM, and Timers. Many developers are stuck in UseEffect Hook Lifecycle, here you will have a deep understanding of how UseEffect Hook works. useEffect holds initial logic inside the component.
What is UseEffect?
UseEffect is a hook in ReactJS, it handles side effects inside the components. UseEffect Hook is basically used for fetching APIs and handling variable component changes. useEffect Hook accepts a function as 1st parameter and 2nd parameter is an array, we can also pass a blank array for only one time call. It’s called the useEffect Hook dependency array.
How does UseEffect Hook use?
UseEffect always initialize first when the component load. it helps to set all initial values in the component.
4 Main Use of UseEffect Hook.
- Every time Call when Code Updates.
- One-Time Call.
- useEffect Hook dependency array.
- Async UseEffect Hook.
Every time Call when Code Update:
When we create useEffect without any dependency array parameter. It will automatically call when the code gets updated. When we don’t pass any dependency array in the 2nd parameter in useEffect it will automatically call when the code gets updated. 2nd parameter is called the useEffect Hook dependency array.
The main use of Useffect Hooks is to fetch API calls when components render. Most users need useEffect Hook one time API call. So when passing a blank array inside the 2nd parameter in UseEffect it will call only once when the component gets rendered. One-Time call useEffect Hook work like uselayoutEffect Hook in ReactJs.
UseEffect Hook dependency array:
When we need to call useEffect with the dependency array changes. the dependency array is a useState Hook. if the dependency array value gets changed call useEffect Hook. this process is most used when the user makes any action as the response we need to call a function. When we pass any state variable inside the 2nd argument it’s called a dependency array. it will automatically call when the variable gets updated.
When someone clicks on that button “Data” value changes, then the UseEffect call. You can check “console” for the updated value.
Async UseEffect Hook:
UseEffect is mainly used for calling API inside it. We can call API with callback function inside the useEffect, but also can use AWAIT inside the useEffect Hook. when we create an async function inside the useEffect it will enable us to use await. by using Await we can easily handle the API Promise. we can also use a useCallback Hook inside useEffect.