Search code examples
reactjsredux-toolkit

Why Should I pass in dispatch as a dependency of useEffect in React?


I've seen a lot of projects that use dispatch as a dependency of useEffect hook in react and I wondered that dispatch is a function and why should I pass it inside useEffect hook?

I guess this is because of our store, I meant it's a reference to our store.


Solution

  • You don't have to pass dispatch as a dependency. The returned references from hooks are known as 'closed-over' or 'captured' values, meaning that the 'hook' in use maintains the references it returns. In the case of useDispatch, its captured reference must remain the same during the lifetime of the component. One of the triggers for a re-render in useEffect is when the arguments you pass as references change.

    With that said, it doesn't make any difference to your code whether you use it as a dependency or not. Usually, in VSCode, it will give you an error if you don't use it, but that is an ESLint error, and we comply with it.

    If you go to https://react-redux.js.org/api/hooks and scroll useDispatch's info section it states the following: "The dispatch function reference will be stable as long as the same store instance is being passed to the <Provider>. Normally, that store instance never changes in an application. However, the React hooks lint rules do not know that dispatch should be stable, and will warn that the dispatch variable should be added to dependency arrays for useEffect and useCallback. The simplest solution is to do just that:"