I'm nearing the end of phase 2 of the Flatiron Software Engineering bootcamp. React was the focus of this phase and, honestly, it was a lot of fun. I really enjoyed learning about props, states, events, controlled components, side effects, client-side routing, etc. However, there was one area of React that was causing some confusion for me... ESLint kept warning me of missing dependencies when using the useEffect hook.
useEffect
The useEffect hook allows us to call a function that is passed into it whenever a component renders. To prevent the function from being called with every render (e.g. when we want to fetch data from an API only once), we provide useEffect with a dependencies array.
In the example above, I'm providing the useEffect hook with an empty array as its dependency. This tells React that it only needs to run this function once.
ESLint Dependency Warning
If, however, our function inside the useEffect hook contains props and/or states, we need to add these as dependencies within the dependency array.
In this example, notice that I'm only including the "currentAircraft" state as the sole dependency. This is all React requires us to include. The setter function "setCurrentAircraft" isn't a state or a prop, it's a function and therefore, is not a dependency. However, ESLint will underline the depenedency array with the message React Hook useEffect has a missing dependency: 'setCurrentAircraft'. Either include it or remove the dependency
. It doesn't hurt to include the setter function as a dependency to appease the warning. But I wanted to find a better solution.
After some forum and documentation searching, I found a great solution in this stack overflow post. In the highest scoring solution, Shubham Khatri recommends adding the eslint-disable-next-line
comment above the dependencies line. So our example above would now look like this:
Reading through the ESLint github, it seems that ESLint isn't able to determine if a dependency is a setter function. At least not yet. Therefore, this workaround is necessary if you dislike the nagging of false warnings. I suppose you could just ignore the warning :)
If you have a different way to deal with this warning, or my interpretation of the warning is a little off, please let me know in the comments! After all, I'm no React expert... yet.
Photo by Lautaro Andreani on Unsplash
Top comments (0)