And what you can do about it
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
.
Have you seen this error before?
In this article, we will take a look at when this warning is triggered and the proper way to get around it.
In order to understand when the exhaustive-deps
warning is triggered, let’s look at some code:
function Profile ({ userId }) {
const [profileData, setProfileData] = useState(null)
const loadCurrentUserProfile = () => {
requestProfileData(userId).then(setProfileData)
}
useEffect(() => loadCurrentUserProfile(), [ userId ])
return (
<ProfileView
data={profileData}
onRefresh={loadCurrentUserProfile}
/>
)
}
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.
useEffect
from ESLint’s perspectiveuserId
changes, load the profile.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.
Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.
Increase Performance of React Applications Via Array JavaScript Methods. We will create a simple event management application in the react to add, update, and delete an event.
This article will walk you through the concepts you would need to know to step into the world of widely used ReactJS.
One of the core ideas in functional programming is composition: building larger things from smaller things. The canonical example of this idea should be familiar with legos.
In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.