Why does React Linter complain about a const variable not being added to the dependency array?

Solution 1:

Whether the "variable"¹ referring the function is let, var, or const is irrelevant. Remember that every time your component needs to be rendered, your component function gets called again, which creates an entirely new execution context with its own const (or let or var) "variable" with a new fetchUserData function assigned to it. useEffect will only ever call the first one of those that's created (because you have a [] dependency array). For this specific situation it may be harmless, but in the general case you run the risk of having closures over stale data, hence the linter warning.

If you don't use any state or props in fetchUserData, you can relocate it inside the useEffect callback, which both gets rid of the error and avoids recreating a function on every render that you're not going to use. (If you do use state or props in fetchUserData, it probably shouldn't only be called once when the component is mounted, but each time the state/props it uses changes.)


¹ More generally, binding (a binding of a name to a storage slot containing a value in the lexical environment object for the execution context of the function call).