visizky
visizky

Reputation: 761

React API call outside useEffect

I was curious to know if making an API request outside of the lifecycle/useEffect is a valid way to make the call?

https://stackblitz.com/edit/react-useeffect-button has two functional components, the parent component makes an API call and passes the data to the child component, initially specified the limit of data to be fetched from the endpoint as 2 and the parent component has a LoadMore function that is passed as a prop along with the data to the child component.

Using the react-slick slider to display the images in the child component and the Load button onClick will call the function LoadMore inside the parent component and then it makes an API call and appends the new data from API to the old Data. The load button will append one Image to the existing images.

is this a good way to make API requests or should it be done only in the lifecycle methods?

Upvotes: 4

Views: 5988

Answers (3)

PrakashT
PrakashT

Reputation: 901

This depends on your needs.

if you think whenever your params change,API call will be triggered. in this case, you should set the API call inside the useEffect.

If you want your API call triggered on page load(ComponentDidMount). In this case, you should set API call inside the useEffect

Otherwise no need to set api call inside useEffect.

In your case no need to set API call inside useEffect. because you hit the API call when the user clicks the button. So no need to use useEffect.

Upvotes: 2

Siraj Alam
Siraj Alam

Reputation: 10025

is this a good way to make API requests outside useEffect/lifecycle.?

It depends on your requirements.

should it be done only in the lifecycle methods?

It depends on your requirements.


There's nothing wrong making API request outside useEffect. But it should be done in some other function or it will cause the request to go on every re-render. And if the response if being saved in a state variable.

Then it will go into the infinite loop.

When do we make the request in useEffect and when by some other function?

Requests that fetch data or send some info at the time of initialization of the component is supposed to be made in componentDidMount/useEffect

And requests that are supposed to be sent on some action (like in your case, onClick) so they are hit according to that event.

There's neither good or bad, it's all about your requirements.

Upvotes: 7

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

If you are making an API call to get data from initial render then using a lifecycle hook is a good approach. In your scenario, you want to make an API request when hitting a button. In that case it can be a simple function without any lifecycle hook method.

The only key part here is that you are maintaining the state and rendering the view from the state.

Upvotes: 2

Related Questions