OBLSK Logo

Fix for React Hook useEffect has a missing dependency: 'dispatch'

If you write a function such as,

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

    useEffect(() =>

    , [])
}
    

You will get the following ESLint error,

        React Hook useEffect has a missing dependency: 'dispatch'
    

The fix is to add dispatch to your dependent array.

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

    useEffect(() => {
        dispatch(fetchTodos())
        // Safe to add dispatch to the dependencies array
    }, [dispatch])
}
        

This tidbit can be found in the info section of React Docs for the useDispatch hook (scroll down a bit after clicking).

Understanding what dependencies to add to the dependent array of the useEffect hook is straight forward, except when that dependency is a function. Often, an easy fix to deal with dependent functions is to define the function inside of the useEffect hook. The definition of dispatch cannot be moved inside of useEffect, so your left scratching your head when ESLint starts telling you to add dispatch to your dependent array or remove the dependent array altogether. It’s confusing until you read the info section of the docs linked to above.

For more information on the [ESLint] 'exhaustive-deps' lint rule, check out https://github.com/facebook/react/issues/14920 and more specifically, one of the comments from Dan Abramov farther down in the issue https://github.com/facebook/react/issues/14920#issuecomment-471070149.

For a deeper dive on useEffect, check out https://overreacted.io/a-complete-guide-to-useeffect/, another great resource from Dan Abramov.