You're unable to read via this Friend Link since it's expired. Learn more
Member-only story
How To Remove useEffect ESLint Warnings in React
without using eslint-disable-line
Are you a React developer? Do you use Hooks and functional components? Do you use ESLint to ensure your code does not do anything spooky? If yes, then I am sure that you have run into the exhaustive-deps
ESLint warning while using useEffect
.
In this article, we will take a look at when this warning is triggered and the proper way to get around it.
When Does ESLint Trigger This Warning?
In order to understand when the exhaustive-deps
warning is triggered, let’s look at some code:
The useEffect
in the code above loads a user’s profile data whenever the ID of the user whose profile is to be displayed changes. Now, let’s put ourselves in ESLint’s shoes and analyze the useEffect
call.
The useEffect
from ESLint’s perspective
- Whenever the
userId
changes, load the profile. - But wait! What if the implementation of the way that we must load the profile changes?
- I must warn the user!
When you look at it from ESLint’s perspective, it does make sense! We know that the implementation of loadCurrentUserProfile
does not change in this case, but ESLint does not. However, ESLint is correct here. In a way, if userId
changes, the implementation of loadCurrentUserProfile
(or the way loadCurrentUserProfile
loads data) changes. This is because loadCurrentUserProfile
is bound to userId
.
We circumvented this little detail and made the useEffect
work by adding userId
directly in the dependency array. This concept will become clearer in a bit, so bear with me.
Removing the Warning
Now, let’s look at how we can remove this warning. And no, we do not remove the warning by adding a //eslint-disable-line
on the dependency array line. We don’t take kindly to those kinds of hacks around here…