Reputation: 893
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
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.
Some useful tips for performance optimization of useEffects:
Source: https://reactjs.org/docs/hooks-effect.html#tips-for-using-effects
Upvotes: 1