The useEffect hook in React
We are going to see how the React useEffect hook works and the types that are there.
It is essential to know this hook in-depth since it has many uses and is widely used in React projects.
If you don't know how it works, you may run into performance issues and render your application components more times than expected.
Don't render a component 1 million times. How UseEffect works
Here we have the typical appearance of the hook:
After React renders a component, it processes the useEffects found. The useEffects are evaluated after the render cycle of a component.
Depending on the two parameters of it, we have 3 types of useEffect. The hook can receive a first function parameter, which is what will be executed, and a second parameter corresponding to an array. Taking this into account, we can break down 3 types:
Only with the first parameter
With an empty array as the second parameter
With an array with variables as the second parameter
1. Only with the first parameter
This useEffect will always be called at the end of the render every time the React component is rendered.
2. With an empty array as the second parameter
It will be executed only the first time the React component is assembled and rendered.
This useEffect is very useful if we want to make calls to an API and get the data to display in the component. We would only get the data at the beginning. Otherwise, we would make API calls with other approaches every time the component was rendered.
3. With an array with variables as the second parameter
This type will always be executed on the first render of the React component and then only whenever the dependencies inside the array change, any of them.
It is crucial to note equality comparisons in JavaScript for this case:
Conclusion
We have reviewed the operation of the hook and its types. It is essential to be clear about how this hook works since it can significantly help when developing and maintaining projects with React. Along with useState, these are the two most common hooks in the React ecosystem.
Here, I share 3 helpful resources that also talk about this topic. I highly recommend them if you want to continue delving into the topics:
https://kentcdodds.com/blog/useeffect-vs-uselayouteffect
I hope you enjoyed the article.
Join my weekly newsletter, where I share articles to help you become a better front-end developer. You'll receive them directly to your inbox.
If you have any questions, feel free to contact me on LinkedIn, Edi Rodriguez, or leave a comment in the post.
See you in the next post.
Have a great day!