underfrankenwood
underfrankenwood

Reputation: 893

Is calling API in useEffect when multiple prop change considered as bad habit or even anti-pattern?

As in the title - is calling API requests in useEffect hook, when there are multiple props in the dependency array considered as bad habit or even anti-pattern?

Consider example:

useEffect(() => {
   dispatch(fetchUsersLocation); // action that calls API
}, [users, location, fetchUsersLocation, someOtherProp]);

So instead of e.g. listening to some event, e.g. click or calling the action on componentDidMount (passing empty dependency array), we are listening to users changes or even location etc.

Thanks

Upvotes: 0

Views: 304

Answers (1)

Irfanullah Jan
Irfanullah Jan

Reputation: 3892

It depends on how often do you really need to call that API. And how often do these items in dependency array change. At a minumim, React docs recommond having a function such as an action creator being included in the dependency array. Please see: Functions in useEffect dependencies array.

Other than that, it depends on your business logic. If you need to fetch fresh data because the users have changed, then it is fine in my opinion. Try using React dev tools option to highlight updates in order to see if the render frequency is acceptable.

enter image description here

Some useful tips for performance optimization of useEffects:

  1. Use multiple useEffects for different concerns.
  2. Skip updates by using conditions inside useEffects.

Source: https://reactjs.org/docs/hooks-effect.html#tips-for-using-effects

Upvotes: 1

Related Questions