-2

How I'm currently using useEffect() (which I only want to run once in the beginning similar to componentDidMount()):

useEffect(() => {
    fetchBusinesses();
  }, []);
const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };
  • 1
    Easiest way is to just move the code inside the `fetchBusinesses` function inside the `useEffect` hook and get rid of `fetchBusinesses` function. You could also move the entire function inside the `useEffect` hook. – Yousaf Dec 27 '21 at 04:59
  • does this answer? https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook – sandeep.kgp Dec 27 '21 at 06:57

2 Answers2

1

There are multiple ways to handle such warnings.

  1. As @Yousaf said, just add the whole function inside your useEffect.
useEffect(() => {
function fetchBusinesses() {
...
}
fetchBusinesses()
}, []);
  1. You can make use of useCallback()
    const fetchBusinesses = useCallback(() => {
      ...
    }, [])
    useEffect(() => {
      fetchBusinesses()
    }, [fetchBusinesses]);
Akshay Shenoy
  • 1,194
  • 8
  • 10
0
useEffect(() => {
  const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"})
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };

  fetchBusinesses();
}, [])
Lin Du
  • 88,126
  • 95
  • 281
  • 483