DEV Community

Discussion on: React Anti-Patterns and Best Practices - Do's and Don'ts

Collapse
 
truemail785 profile image
Ozair • Edited

Is it a good idea to leave the dependency array of useCallback empty so that the function is only initialized once? Because the callback will be generating output OR performing something based on the up-to-date state variables. Why do we reinitialize the function on the value changes if it is using the up-to-date state values directly. Or is it? Maybe we are re-initializing the function so that it doesn't use the old values. Is that the case here?

Collapse
 
perssondennis profile image
Dennis Persson

It is fine to leave the dependency array empty if you really don't have any dependencies it is dependent on. If it is dependent on state variables or functions, you should add all of them. If you don't do that, the function you have wrapped in useCallback will use an old instance of the dependency if the dependency reference updates.

Note that if you have a function as a dependency to a useCallback, that function would also need to be a useCallback function, because if that would be a normal function in a React component, the useCallback function would be recreated every render since the normal function's reference changes every time.

As I wrote in the article, you should always add all dependencies to all hooks with dependencies (useEffect, useCallback, useMemo). Normally it's completely safe to add all dependencies to useCallback and useMemo, it won't infer any bugs (unless you are doing strange things in your code, for example if it's very important for the useMemo to run once).

With useEffects it's more difficult. You should still add all dependencies to it. But as described in the article (tip number 7), it can be tricky to do. If you see a useEffect with a missing dependency in some old code. Don't just add it without ensuring that the functionality still works, because the code's behavior may change.

Sometimes it is better to don't touch old code that works. And if you need to touch it, consider to refactor it. I have written another article describing how to deal with code changes. I think it's a good reading to learn about why it is important to be thoughtful when altering old code.

Collapse
 
truemail785 profile image
Ozair

Thanks for the detailed explanation.