useEffect lets us perform side effects in functional components.
Side effects mean all the operations that affect the component and can not be done during rendering.
Ex:- Fetch Data, Subscription, or Manually Changing the DOM
in the old way we had to use,
ComponentDidMount to fetch data from APIs
ComponentDidUpdate to send data when something changed
ComponentWillUnmount to unsubscribe from events
useEffect runs after every render including the first one. React guarantees the DOM has been updated by the time it runs the effects when we use useEffect, we are telling react that our component needs to do something after rendering.
A common use of useEffect is to unsubscribe from events before the component is finally unmounted.
To achieve that behavior with useEffect, you just need to return a function. React will take care of everything and run it when it is time to clean up.
For more details about Cleanups, you can refer to this article.
Running all effects on every render might lead to performance issues. To fix that we need to tell react we can provide a second argument to useEffect which is a dependency array.
If we pass an empty array as the second argument the function will run just once, after the first render. This means the effect doesn’t depend on any values from props or state. so it never needs to re-run.
A Summary of Dependency Array
No dependency array — The function runs after every render.
Empty dependency array — The function runs after the first render.
Dependency array with some values — The function runs only if any of those values changed.
Thanks for reading.
Image credits to Unsplash.