reactjsreact-hookseslint-plugin-react-hooks

How to fix this "React Hook useEffect has a missing dependency" warning?


Here's my file:

// useFetcher.js
import { useEffect, useState } from "react";

export default function useFetcher(action) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);
  async function loadData() {
    try {
      setLoading(true);
      const actionData = await action();
      setData(actionData);
    } catch (e) {
      setError(e);
    } finally {
      setLoading(false);
    }
  }
  useEffect(() => {
    loadData();
  }, [action]);
  return [data, loading, error];
}

On line 21, eslint complaints that:

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

How can I fix this?


Solution

  • The best way here would be to define your async function inside the useEffect:

    export default function useFetcher(action) {
      const [loading, setLoading] = useState(false);
      const [error, setError] = useState(null);
      const [data, setData] = useState(null);
    
      useEffect(() => {
        async function loadData() {
          try {
            setLoading(true);
            const actionData = await action();
            setData(actionData);
          } catch (e) {
            setError(e);
          } finally {
            setLoading(false);
          }
        }
    
        loadData();
      }, [action]);
      return [data, loading, error];
    }
    
    

    More info in the docs.