0

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?

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting. I'm new to hooks, is there any documentation on this block scoping?
I highly recommend reading this post by D.Abramov: overreacted.io/a-complete-guide-to-useeffect
"If you’re not comfortable with deep dives, you might want to wait until these explanations appear elsewhere. Just like when React came out in 2013, it will take some time for people to recognize a different mental model and teach it." Love the post so far!
0

Add the loadData function to the array in your useEffect. This will get rid of the complaint:

useEffect(() => {
  loadData();
}, [action, loadData]);

3 Comments

Now it tells me The 'loadData' function makes the dependencies of useEffect Hook (at line 21) change on every render. Move it inside the useEffect callback. Alternatively, wrap the 'loadData' definition into its own useCallback() Hook
If I move loadData inside the callback of useEffect, the warning disappears. I'm new to hooks, Is this good practice?
A good linter will tell you that's of no use unless loadData came from a useCallback that has action as a dependency. If you use vscode with eslint plugin and an app created with latest create-react-app you would see the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.