Paul Razvan Berg
Paul Razvan Berg

Reputation: 21390

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?

Upvotes: 0

Views: 2447

Answers (2)

Clarity
Clarity

Reputation: 10873

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.

Upvotes: 1

complexSandwich
complexSandwich

Reputation: 595

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

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

Upvotes: 0

Related Questions