7

If I use this

  useEffect(() => {
dispatch(fetchToDos())}, [debouncedToDo, loginInfo.isLogin])

I get this warning

React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps

If I include 'dispatch' in dependency array the warning is gone.

Like this:

  useEffect(() => {
dispatch(fetchToDos())}, [dispatch, debouncedToDo, loginInfo.isLogin])
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
George Hutanu
  • 139
  • 1
  • 5

1 Answers1

13

Yes, dispatch is safe to add to an useEffect hook's dependency array.

From the docs

INFO

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:

export const Todos() = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchTodos())
  // Safe to add dispatch to the dependencies array
  }, [dispatch])
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181