Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 445
visizky Avatar asked Dec 23 '22 19:12

visizky


2 Answers

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.

like image 140
Siraj Alam Avatar answered Jan 10 '23 20:01

Siraj Alam


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.

like image 40
Muhammad Zeeshan Avatar answered Jan 10 '23 20:01

Muhammad Zeeshan