Can I call separate function in useEffect?

TL;DR
use useCallback()


First of all, using a function as a dependency is very dangerous. If that function causes a state change, then the subsequent re-render will invoke the function again (through useEffect)… and an infinite loop begins.

One thing you can do, as many suggest here, is to create the function within the useEffect() method itself.

 useEffect(() => {
    function getData() {
      fetch(`https://jsonplaceholder.typicode.com/${query}`)
        .then(response => response.json())
        .then(json => setData(json));
      }
    }

    getData();
    console.log("useEffect ran...");
  }, [query]);
}

or simply

 useEffect(() => {
    (() => {
       fetch(`https://jsonplaceholder.typicode.com/${query}`)
      .then(response => response.json())
      .then(json => setData(json)
     )();
  }, [query]);
}

Having said that, sometimes you want to still declare the function outside the useEffect for code-reuse. This time you need to make sure it is not re-created during each render. For that, you can either

  1. declare the function outside the component — which forces you to pass all variables as arguments…. which is a pain

  2. wrap it inside useMemo() or useCallback()

Here’s an example

    const getData = useCallback(()=>{...}, []);

Leave a Comment