Two useEffect vs two API calls inside one useEffect

Viewed 4825

When component mounts I need to get data from two API endponints. For now I have:

  useEffect(() => {
    dispatch(loadSomeDataOne());
  }, [dispatch]);

  useEffect(() => {
    dispatch(loadSomeDataTwo());
  }, [dispatch]);

I was thinking to do it within one useEffect:

  useEffect(() => {
    dispatch(loadSomeDataOne());
    dispatch(loadSomeDataTwo());
  }, [dispatch]);

Is there some difference between these two solutions? Which one's better?

2 Answers

Nope. using multiple useEffect is mostly for subscribing the side effects to different variable updates. For example you might have:

  useEffect(() => {
    dispatch(loadSomeDataOne(varA));
  }, [varA]);

  useEffect(() => {
    dispatch(loadSomeDataTwo(varB));
  }, [varB]);

This way, only the desired useEffect executes when either varA or varB is updated. If you want everything to run at the same time, then you just need 1 useEffect.

In this article, you will understand about useEffect https://www.robinwieruch.de/react-hooks-fetch-data For me: Because you want to call API only when component mounting you can write code like that:

 useEffect(() => {
    dispatch(loadSomeDataOne());
    dispatch(loadSomeDataTwo());
  }, []);

That means you only want two function load data call once

Related