Search code examples
reactjsdependenciesstateuse-effect

React Why is it considered a performance optimisation to include functions in the list of dependencies?


According to the docs we don't want to omit functions from the dependencies of a useEffect(). Why is this? What are the performance implications?


Solution

  • If you omit functions and your component grows, there might be a chance that at some point in time your function may need some props and indirectly your effects may lie about dependencies.

    That's why the recommendation is to hoist functions that don’t need props or state outside of your component and pull the ones that are used only by an effect inside of that effect. If useEffect still needs function as dependencies then wrap them in useCallback.

    This way we no longer have to think about the transitive dependencies. Our dependencies array isn’t lying anymore: we truly aren’t using anything from the outer scope of the component in our effect. And your code is performant and optimal.

    refer more here: moving-functions-inside-effects