0

I'm not entirely clear why we need to include all* dependencies for useEffect

For example

import { apiCall } from 'api'; 

const App = () => {
    
    useEffect(() => {
        apiCall(); 
    }, [])
    
    return <p>hi</p>

}

As I understand it, this is wrong. I should include apiCall in the dependency array. I'm just not quite clear why that's necessary? I only want this to run once, when the component mounts. Why do I need to include any other information?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
J Seabolt
  • 2,576
  • 5
  • 25
  • 57
  • You don't have to, it's just *recommended* by some (and not preferred by others) – CertainPerformance May 19 '21 at 17:30
  • 1
    IIRC this has also been somewhat mitigated lately. In any case, exhaustive-deps is meant to target component variables, not external ones. See https://stackoverflow.com/q/56972415/438992 for some details and the update (I haven't dug into it yet). – Dave Newton May 19 '21 at 17:31
  • It is not necessary. The [documentation](https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies) mentions that _"function outside of your component is guaranteed to not reference any props or state, and also doesn’t need to be in the list of dependencies."_ – Emile Bergeron May 19 '21 at 17:34

0 Answers0